What is order of calling constructor and destructor in C++?

(Last Updated On: March 17, 2018)

Order of execution of constructors and destructors in C++ is frequently asked interview question. For this question, we have to answer c++ constructor call order and destructor call order  in inheritance relationship with a program example.


[NOTE: During answering c++ inheritance destructor order question, it is better to include answer for multiple inheritance constructor call order also that I have explained as a notes in bottom of this post and Constructors Destructors call order for multiple composed objects in a C++ class]


Answer: C++ constructor call order will be from top to down that is from base class to derived class and c++ destructor call order will be in reverse order.

Below is the example of constructor destructor call order for multi-level inheritance, in which Device class is the base class and Mobile class is derived from Device base class and then Android class is derived from Mobile class as a base class.

When we create the object of Android class, order of invocation of constructor and destructor will be as below
Constructor: Device
Constructor: Mobile
Constructor: Android
Destructor : Android
Destructor : Mobile
Destructor : Device


Example of order of constructor and destructor in c++ in multilevel inheritance.




In multiple inheritance, for exampleclass Gadgets:public Mobile,public Tablet”, order of constructor call will be of Mobile, Tablet and then derived class i.e. Gadgets.

Example: C++ multiple inheritance constructor call order



Constructor: Mobile
Constructor: Tablet
Constructor: These are my Gadgets
Destructor : Destroying Gadgets
Destructor : Tablet
Destructor : Mobile


Recommend to read another important interview question Why to use C++ Virtual destructor in a C++ class?

In short, virtual desturctor is used to maintain the destructors call order in a polymorphic class in an inheritance hierarchy.