Inherited Constructors And Destructors

A base class object can exist without any object being derived from it. On the other hand, a derived class object must encompass by definition all members of the base class and all members declared within the derived class itself. Hence, the base class part of an object must be constructed before the derived class part. And the other way around, a derived class object must be destroyed before its base is destroyed. For multiple inheritance the rule is the same: bases are constructed before derived objects and destroyed after derived objects. In the following program two different classes are declared: BaseClass and DerivedClass, which inherits from BaseClass. In order to show the order of constructor and destructor execution, each constructor and destructor prints a message to the console.

Example


#include <iostream>
#include <string>
using namespace std;

class BaseClass
{
public:
     BaseClass()
     {
           cout << "BaseClass constructor\n";
     }

     ~BaseClass()
     {
           cout << "BaseClass destructor\n";
     }
};

class DerivedClass: public BaseClass
{

public:
     DerivedClass()
     {
           cout << "DerivedClass constructor\n";
     }

     ~DerivedClass()
     {
           cout << "DerivedClass destructor\n";
     }
};

int main()
{
    DerivedClass d;
}

Output

BaseClass constructor
DerivedClass constructor
DerivedClass destructor
BaseClass destructor