The sequence of execution of constructors and destructors in inheritance
Whenever an object of most derived class is declared, first of all the constructor function of the highest base class gets invoked and then the hierarchy is followed downwards.
Whenever an object of most derived class goes out of scope, first of all the destructor functions of the most derived class gets invoked and then the hierarchy is followed upwards.
Single Inheritance
//Sequence of execution of constructors and destructors //single inheritance #include<iostream> using namespace std; class A { public: A() { cout<<"Constructor function of class A"<<endl; } ~A() { cout<<"Destructor function of class A"<<endl; } }; class B:public A { public: B() { cout<<"Constructor function of class B"<<endl; } ~B() { cout<<"Destructor function of class B"<<endl; } }; int main() { B b1; return(0); }
Output:
Constructor function of class A
Constructor function of class B
Destructor function of class B
Destructor function of class A
Multi Level Inheritance
//Sequence of execution of constructors and destructors //Multilevel inheritance #include<iostream> using namespace std; class A { public: A() { cout<<"Constructor function of class A"<<endl; } ~A() { cout<<"Destructor function of class A"<<endl; } }; class B:public A { public: B() { cout<<"Constructor function of class B"<<endl; } ~B() { cout<<"Destructor function of class B"<<endl; } }; class C:public B { public: C() { cout<<"Constructor function of class C"<<endl; } ~C() { cout<<"Destructor function of class C"<<endl; } }; int main() { C b1; return(0); }
Output:
Constructor function of class A
Constructor function of class B
Constructor function of class C
Destructor function of class C
Destructor function of class B
Destructor function of class A