Open In App

Order of Constructor/ Destructor Call in C++

Last Updated : 14 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Constructors 
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 invocation is that the base class’s default constructor will be invoked first and then the derived class’s default constructor will be invoked.

Why the base class’s constructor is called on creating an object of derived class?

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. 

C++




// C++ program to show the order of constructor call
// in single inheritance
   
#include <iostream>
using namespace std;
  
// base class
class Parent
{
    public:
      
    // base class constructor
    Parent()
    {
        cout << "Inside base class" << endl;
    }
};
  
// sub class
class Child : public Parent
{
    public:
      
    //sub class constructor
    Child()
    {
        cout << "Inside sub class" << endl;
    }
};
  
// main function
int main() {
       
    // creating object of sub class
    Child obj;
      
    return 0;


Output:  

Inside base class
Inside sub class

Order of constructor call for Multiple Inheritance

For multiple inheritance order of constructor call is, the base class’s constructors are called in the order of inheritance and then the derived class’s constructor. 

C++




// C++ program to show the order of constructor calls 
// in Multiple Inheritance
  
#include <iostream>
using namespace std;
  
// first base class
class Parent1
{   
     
    public:
      
    // first base class's Constructor    
    Parent1()
    {
        cout << "Inside first base class" << endl;
    }
};
  
// second base class
class Parent2
{
    public:
      
    // second base class's Constructor
    Parent2()
    {
        cout << "Inside second base class" << endl;
    }
};
  
// child class inherits Parent1 and Parent2
class Child : public Parent1, public Parent2
{
    public:
      
    // child class's Constructor
    Child()
    {
        cout << "Inside child class" << endl;
    }
};
  
// main function
int main() {
      
    // creating object of class Child
    Child obj1;
    return 0;


Output:  

Inside first base class
Inside second base class
Inside child class

Order of constructor and Destructor call for a given order of Inheritance

 How to call the parameterized constructor of base class in derived class constructor?

To call the parameterized constructor of base class when derived class’s parameterized constructor is called, you have to explicitly specify the base class’s parameterized constructor in derived class as shown in below program:

C++




// C++ program to show how to call parameterized Constructor
// of base class when derived class's Constructor is called
  
#include <iostream>
using namespace std;
  
// base class
class Parent {
    int x;
  
public:
    // base class's parameterized constructor
    Parent(int i)
    {
        x = i;
        cout << "Inside base class's parameterized "
                "constructor"
             << endl;
    }
};
  
// sub class
class Child : public Parent {
public:
    // sub class's parameterized constructor
    Child(int x): Parent(x)
    {
        cout << "Inside sub class's parameterized "
                "constructor"
             << endl;
    }
};
  
// main function
int main()
{
  
    // creating object of class Child
    Child obj1(10);
    return 0;
}


Output: 

Inside base class's parameterized constructor
Inside sub class's parameterized constructor

Important Points

  • Whenever the derived class’s default constructor is called, the base class’s default constructor is called automatically.
  • To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly.
  • The parameterized constructor of base class cannot be called in default constructor of sub class, it should be called in the parameterized constructor of sub class.

Destructors in C++ are called in the opposite order of that of Constructors.



Similar Reads

Is it possible to call constructor and destructor explicitly in C++?
A constructor is a special member function that is automatically called by the compiler when an object is created and the destructor is also a special member function that is also implicitly called by the compiler when the object goes out of scope. They are also called when a dynamically allocated object is allocated and destroyed, a new operator a
3 min read
Difference Between Call by Value and Call by Reference in C++
In C++ programming we have different ways to pass arguments to functions mainly by Call by Value and Call by Reference method. These two methods differ by the types of values passed through them as parameters. Before we look into the call-by-value and call-by-reference methods, we first need to know what are actual and formal parameters. The actual
4 min read
Difference Between Constructor and Destructor in C++
Constructor: A constructor is a member function of a class that has the same name as the class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of the class. It is called whenever an instance of the class is created. It can be defined manually with argument
3 min read
How to detect Stack Unwinding in a Destructor in C++?
What is Stack Unwinding? Stack unwinding is the process of executing destructors for all local objects when an exception propagates out of a function. It happens when an exception is thrown and not caught within the same function. When this occurs, the destructors for all objects with automatic storage duration declared in that function are called
4 min read
Virtual Destructor
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, the following program results in undefined behavior. C/C++ Code // CPP program without virtual destructor // causing u
2 min read
Private Destructor in C++
Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor private. What is the use of private destructor? Whenever we want to control the destruction of objects of a class, we make the destructor private. For dynamically created objects, it
4 min read
Pure Virtual Destructor in C++
A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order. As a result, for a pure virtual destructor, you m
4 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
Destructor for Dynamic Array in C++
Dynamic memory allocation in C++ allows us to allocate memory during program execution using the pointers. This memory is wholly managed by the programmer from allocation to deallocation. So, when we declare a dynamic member in a class, it is our responsibility to deallocate the memory for that class when the object is destroyed. In this article, w
3 min read
Sort first k values in ascending order and remaining n-k values in descending order
Given an array of size n, arrange the first k elements of the array in ascending order and the remaining n-k elements in descending order. Examples: Input: arr[] = {5, 4, 6, 2, 1, 3, 8, 9, -1}, k = 4 Output: 2 4 5 6 9 8 3 1 -1 Input: arr[] = {5, 4, 6}, k = 2 Output: 4 5 6 Algorithm: Store the first k elements in an array and sort that in ascending
11 min read
Article Tags :
Practice Tags :