What is the order in which the destructors and the constructors are called in C++? Using the examples of some Base classes and Derived Classes
What is the order in which the destructors and the constructors are called in C++? Using the examples of some Base classes and Derived Classes
The order is:
Example:
class B
{
public:
B()
{
cout<<"Construct B"<<endl;
}
virtual ~B()
{
cout<<"Destruct B"<<endl;
}
};
class D : public B
{
public:
D()
{
cout<<"Construct D"<<endl;
}
virtual ~D()
{
cout<<"Destruct D"<<endl;
}
};
int main(int argc, char **argv)
{
D d;
return 0;
}
Output of example:
Construct B
Construct D
Destruct D
Destruct B
Multiple levels of inheritance works like a stack:
If you consider pushing an item onto the stack as construction, and taking it off as destruction, then you can look at multiple levels of inheritance like a stack.
This works for any number of levels.
Example D2 derives from D derives from B.
Push B on the stack, push D on the stack, push D2 on the stack. So the construction order is B, D, D2. Then to find out destruction order start popping. D2, D, B
More complicated examples:
For more complicated examples, please see the link provided by @JaredPar
A detailed description of these events, including virtual and multiple inheritance is available at the C++ FAQ Lite. Section 25.14 and 25.15
https://isocpp.org/wiki/faq/multiple-inheritance#mi-vi-ctor-order
Also, keep in mind that while array elements are constructed first -> last, they are destructed in the reverse order: last -> first.
This is clearly described at order-dtors-for-members. Basically, the rule is "First constructed, last destructed."
Constructors calling order:
Destructors are called in reversed order of called constructors.
Example:
#include <iostream>
struct base0 { base0(){printf("%s\n", __func__);};~base0(){printf("%s\n", __func__);}; };
struct base1 { base1(){printf("%s\n", __func__);}; ~base1(){printf("%s\n", __func__);};};
struct member0 { member0(){printf("%s\n", __func__);}; ~member0(){printf("%s\n", __func__);};};
struct member1 { member1(){printf("%s\n", __func__);}; ~member1(){printf("%s\n", __func__);};};
struct local0 { local0(){printf("%s\n", __func__);}; ~local0(){printf("%s\n", __func__);}; };
struct local1 { local1(){printf("%s\n", __func__);}; ~local1(){printf("%s\n", __func__);};};
struct derived: base0, base1
{
member0 m0_;
member1 m1_;
derived()
{
printf("%s\n", __func__);
local0 l0;
local1 l1;
}
~derived(){printf("%s\n", __func__);};
};
int main()
{
derived d;
}
Output:
base0
base1
member0
member1
derived
local0
local1
~local1
~local0
~derived
~member1
~member0
~base1
~base0