Order of Constructor Call in C++

  • October 23, 2022
  • C++
Accessing Elements

If we inherit a class from another class and create an object of the derived class, it is obvious that the derived class’s default constructor will be invoked, but first, the default constructors of all base classes will be invoked.

The data members and member functions of the base class are automatically included in the derived class based on the access specifier, but the definition of these members is only available in the base class. When we create an object of a derived class, all of its members must be initialized, but the inherited members in the derived class can only be initialized by the base class’s constructor because their definition exists only in the base class. This is why the base class’s constructor is called first to initialize all inherited members.

Example:
#include<iostream>
using namespace std;

//base class
class Device{

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

//derived class
class Mobile:public Device{

public:

	Mobile(){
	    cout<<"Constructor: Mobile\n";
	    
	}
	~Mobile(){
	    cout<<"Destructor : Mobile\n";
	    
	}
};

//derived class
class Android:public Mobile{

public:

	Android(){
	    cout<<"Constructor: Android\n";
	    
	}
	~Android(){
	    cout<<"Destructor : Android\n";
	    
	}
};



int main()
{
	Android _android; // create the object that will call required constructors	

	return 0;
}
Output:
Constructor: Device
Constructor: Mobile
Constructor: Android
Destructor : Android
Destructor : Mobile
Destructor : Device

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 the base class inside the parameterized constructor of subclass, we have to mention it explicitly.
  • The parameterized constructor of a base class cannot be called in the default constructor of the subclass, it should be called in the parameterized constructor of the subclass.

Note: also read about Types of Inheritance in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

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