Whenever an object is created in C++, its constructor is called. The constructor is responsible for initializing the object's state and allocating any necessary resources. The destructor serves as the counterpart to the constructor. It's responsible for releasing resources and performing cleanup operations. Let's discuss the order in which constructors and destructors are called while using inheritance in C++.
The constructor calling order refers to the sequence in which constructors are invoked during object initialization. The constructor calling order when using inheritance is
The destructor calling order refers to the sequence in which destructors are invoked during object destruction. The Destructor calling order when using inheritance is
The diagram below demonstrates the constructor and destructor calling orders while using inheritance:
The parent class's constructor is called before the child class's constructor. In contrast, the destructor of the child class is called before the destructor of the parent class.
The following code demonstrates the constructor and destructor calling orders:
#include <iostream>using namespace std;//base classclass Animal {public:Animal() //Constructor of Parent class{cout << "Constructor of Animal called. \n";}~Animal() //Destructor of Parent class{cout << "Destructor of Animal called. \n";}};// Derived classclass Cat : public Animal { //The Cat class inheriting the attributes of Animal class herepublic:Cat() //Constructor of Child class{cout << "Constructor of Cat called. \n";}~Cat() //Destructor of Child class{cout << "Destructor of Cat called. \n";}};int main(){{//Brackets are used to limit the scope of objectCat C; //Object initialization}return 0;}
Line 5: We make the parent class Animal
.
Lines 7–10: Now we declare the constructor of the Animal
class and display a message indicating that the constructor of the Animal
class has been invoked.
Lines 11–14: Here we make the destructor of the Animal
class and display a message indicating that the destructor of the Animal
class has been invoked..
Line 18: Create the derived class Cat
by inheriting the from the parent class Animal
.
Lines 20–23: Here we make the constructor of the Cat
class and display a message indicating that the constructor of the Cat
class has been invoked.
Lines 24–27: Now we make the destructor of the Cat
class and display a message indicating that the destructor of the Cat
class has been invoked.
Lines 32–34: Finally, we make an object C
of the class Cat
and observe the calling orders of the constructors and destructors of Animal
and Cat
classes.
Free Resources