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
I must add to the previous answers because everyone seems to be ignoring it
When you have a derived class instance being created, it is true that the code inside the constructor of the base will be called before the code inside the constructor of the derived, but keep in mind that the derived is still technically "created" before the base.
And when you have the derived class destructor being called, it is true that the code inside the derived destructor is called before the code inside the base destructor, but also keep in mind that the base is destroyed before the derived.
When I am saying created/destroyed I am actually referring to allocated/deallocated.
If you look at the memory layout of these instances, you will see that the derived instance composes the base instance. For example:
Memory of derived: 0x00001110 to 0x00001120
Memory of base : 0x00001114 to 0x00001118
Therefore, the derived class must be allocated BEFORE the base in the construction. And the derived class must be deallocated AFTER the base in the destruction.
If you have the following code:
class Base
{
public:
Base()
{
std::cout << "\n Base created";
}
virtual ~Base()
{
std::cout << "\n Base destroyed";
}
}
class Derived : public Base
{
public:
Derived()
// Derived is allocated here
// then Base constructor is called to allocate base and prepare it
{
std::cout << "\n Derived created";
}
~Derived()
{
std::cout << "\n Derived destroyed";
}
// Base destructor is called here
// then Derived is deallocated
}
So if you created Derived d; and had it go out of scope, then you will get the output in @Brian's answer. But the object behavior in memory is not really the in same order, it is more like this:
Construction:
Derived allocated
Base allocated
Base constructor called
Derived constructor called
Destruction:
Derived destructor called
Base destructor called
Base deallocated
Derived deallocated