Constructor and Destructor in Inheritance

Invocation of constructors and destructors depends on the type of inheritance being implemented. We have presented you the sequence in which constructors and destructors get called in single and multiple inheritance.

  1.  Constructor and destructor in single inheritance

  • Base class constructors are called first and the derived class constructors are called next in single inheritance.
  • Destructor is called in reverse sequence of constructor invocation i.e. The destructor of the derived class is called first and the destructor of the base is called next.
//eg of constructor and destructor in single inheritance
#include<iostream>
using namespace std;
class base
{
public:
    base()
    {
        cout<<"base class constructor"<<endl;
    } ~base()
    {
        cout<<"base class destructor"<<endl;
    }
};
class derived:public base
{
public:
    derived()
    {
        cout<<"derived class constructor"<<endl;
    } ~derived()
    {
        cout<<"derived class destructor"<<endl;
    }
};
int main()
{
    derived d;
    return 0;
}

The output of the program is:

consThe output illustrates the sequence of call on constructor and destructor in single inheritance.

2. Constructor and destructor in multiple inheritance

  • Constructors from all base class are invoked first and the derived class constructor is called.
  • Order of constructor invocation depends on the order of how the base is inherited.
  • For example:
class D:public B, public C { 
    //… 
 }

Here, B is inherited first, so the constructor of class B is called first and then constructor of class C is called next.

  •  However, the destructor of derived class is called first and then destructor of the base class which is mentioned in the derived class declaration is called from last towards first in sequentially.
//example of constructor and destructor in multiple inheritance
#include<iostream>
using namespace std;
class base_one
{
public:
    base_one()
    {
        cout<<"base_one class constructor"<<endl;
    } 
    ~base_one()
    {
        cout<<"base_one class destructor"<<endl;
    }
};
class base_two
{
public:
    base_two()
    {
        cout<<"base_two class constructor"<<endl;
    } 
    ~base_two()
    {
        cout<<"base_two class destructor"<<endl;
    }
};
class derived:public base_one, public base_two
{
public:
    derived()
    {
        cout<<"derived class constructor"<<endl;
    } 
    ~derived()
    {
        cout<<"derived class destructor"<<endl;
    }
};
int main()
{
    derived d;
    return 0;
}

The output of the program is:

multiple-cons

C++ Multipath inheritance
C++ Virtual Function