Wednesday, March 28, 2018

Write a C++ program to illustrate the order execution of contructor and destructor in inheritance.


AIM: Write a C++ program to illustrate the order execution of contructor and destructor in inheritance.
THEORY:
Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class.
If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that the default constructor of all of the base classes will be invoke, i.e the order of invokation is that the base class’s default constructor will be invoked first and then the derived class’s default constructor will be invoked.
To understand this you will have to recall your knowledge on inheritance. What happens when a class is inherited from other? The data members and member functions of base class comes automatically in derived class based on the access specifier but the definition of these members exists in base class only. So when we create an object of derived class, all of the members of derived class must be initialized but the inherited members in derived class can only be initialized by the base class’s constructor as the definition of these members exists in base class only. This is why the constructor of base class is called first to initialize all the inherited members.

SOURCE CODE:
#include<iostream>
using namespace std;
class A{
            public:
            A(){
              cout<<"\n zero arguement constructor of base class a";      
            }         
            ~A(){
                        cout<<"\n destructor of class A";
            }
};
class B{
            public:
            B(){
                        cout<<"\n zero arguement constructor of base class b";
            }
            ~B(){
               cout<<"\n destructor of base class b";        
            }         
};
class C:public A,B{
            public:
            C(){
              cout<<"\n zero arguement constructor of desired class c";  
            }         
            ~C(){
                        cout<<"\n destructor of class C";
            }
};
int main(){
            C obj;
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home