Signup/Sign In

Order of Constructor Call with Inheritance in C++

In this tutorial, we will learn about the Order of Constructor Call with Inheritance in C++. If you are not familiar with the Constructor in C++, you can learn about it from C++ Constructors tutorial.

Order of constructor call

Base class Default Constructor in Derived class Constructors:

When we derive a class from the base class then all the data members of the base class will become a member of the derived class. We use the constructor to initialize the data members and here the obvious case is when the data is inherited into the derived class who will be responsible to initialize them? To initialize the inherited data membres constructor is necessary and that's why the constructor of the base class is called first. In the program given below, we can see the sequence of execution of constructors in inheritance is given below:

#include <iostream>
using namespace std;
class Base
{
   int x;

public:
   // default constructor
   Base()
   {
      cout << "Base default constructor\n";
   }
};

class Derived : public Base
{
   int y;

public:
   // default constructor
   Derived()
   {
      cout << "Derived default constructor\n";
   }
   // parameterized constructor
   Derived(int i)
   {
      cout << "Derived parameterized constructor\n";
   }
};

int main()
{
   Base b;
   Derived d1;
   Derived d2(10);
}


Base default constructor
Base default constructor
Derived default constructor
Base default constructor
Derived parameterized constructor

Base class Parameterized Constructor in Derived class Constructor:

Let's see how we can call the parameterized constructor in the Derived class, We need to explicitly define the calling for the parameterized constructor of the derived class using : operator while defining the parameterized constructor in a derived class.

#include <iostream>
using namespace std;
class Base
{ 
    int x;
    public:
    // parameterized constructor
    Base(int i)
    { 
        x = i;
        cout << "Base Parameterized Constructor\n";
    }
};

class Derived: public Base
{ 
    int y;
    public:
    // parameterized constructor
    Derived(int j):Base(j)
    { 
        y = j;
        cout << "Derived Parameterized Constructor\n";
    }
};

int main()
{
    Derived d(10) ;
}


Base Parameterized Constructor
Derived Parameterized Constructor

 

Here are some basic rules to figure out the Order of Constructor Call with Inheritance in C++.

  • Construction always starts with the base class. If there are multiple base classes then, construction starts with the leftmost base. If there is a virtual inheritance then it's given higher preference).

  • Then the member fields are constructed. They are initialized in the order they are declared

  • Finally, the class itself is constructed

  • The order of the destructor is exactly the reverse

Related Tutorials: