Cpp Tutorial: Order of Constructor and Destructor Call in inheritance in C++

In this chapter we shall see the order of Constructor and Destructor in inheritance

1. Order of Constructor and destructor call for simple inheritance
2. Order of Constructor and destructor call for multiple inheritance

1. Order of Constructor and destructor call for simple inheritance

In this topic we shall see how the constructor and destructor call will occur when there is a simple inheritance.

During simple inheritance, base class constructor will be called followed by derived class constructor.

Then destruction will happen in reverse. It means, derived class destructor will be called first and then base class destructor.

Example:

#include <iostream>       // std::cout

// for more tutorials visit www.ProDeveloperTutorial.com

using namespace std;

class Base 
{ 
  public: 
    Base()      
    { 
        cout<<"Constructor Base \n"; 
    } 
    ~Base()
    {
        cout<<"Destructor Base \n"; 
    }
   
}; 

class Derived: public Base 
{ 
  public: 
    Derived()      
    { 
        cout<<"Constructor Derived \n"; 
    } 
    
    ~Derived() 
    { 
        cout<<"Destructor Derived \n"; 
    } 
}; 
  
int main(void) 
{ 

  Derived d;

  return 0; 
} 

Output:

Constructor Base
Constructor Derived
Destructor Derived
Destructor Base

2. Order of Constructor and destructor call for multiple inheritance

During multiple inheritance, the constructor of base class will be called first.

The order of constructor called will be in the order of constructor defined.

For example if you have defined like this “class Derived: public A, public B”, then Constructor of class A will be called, then constructor of class B will be called.

Example:

#include <iostream>       // std::cout

// for more tutorials visit www.ProDeveloperTutorial.com

using namespace std;

class A 
{ 
  public: 
    A()      
    { 
        cout<<"Constructor A \n"; 
    } 
    ~A()
    {
        cout<<"Destructor A \n"; 
    }
   
}; 

class B
{ 
  public: 
    B()      
    { 
        cout<<"Constructor B \n"; 
    } 
    ~B()
    {
        cout<<"Destructor B \n"; 
    }
   
}; 


class Derived: public A, public B 
{ 
  public: 
    Derived()      
    { 
        cout<<"Constructor Derived \n"; 
    } 
    
    ~Derived() 
    { 
        cout<<"Destructor Derived \n"; 
    } 
}; 
  
int main(void) 
{ 

  Derived d;

  return 0; 
} 

Output:

Constructor A
Constructor B
Constructor Derived
Destructor Derived
Destructor B
Destructor A
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *