Multiple Inheritance - Constructors And Destructors
In case of a class inheriting from more classes, the order of construction is:
bases first, in the order in which they are declared, derived class later.
So, given a class
A derived both from
B and
C:
class A: public B, public C
B’s constructor is called first, then
C’s is called and finally A’s.
For destructors the opposite order is followed.
In the program below three different classes are declared:
BaseClass1,
BaseClass2
and
DerivedClass, which inherits from
BaseClass1 and
BaseClass2.
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 <iostream>
using namespace std;
class BaseClass1
{
public:
BaseClass1()
{
cout << "BaseClass1 constructor\n";
}
~BaseClass1()
{
cout << "BaseClass1 destructor\n";
}
};
class BaseClass2
{
public:
BaseClass2()
{
cout << "BaseClass2 constructor\n";
}
~BaseClass2()
{
cout << "BaseClass2 destructor\n";
}
};
class DerivedClass: public BaseClass1, public BaseClass2
{
public:
DerivedClass()
{
cout << "DerivedClass constructor\n";
}
~DerivedClass()
{
cout << "DerivedClass destructor\n";
}
};
int main()
{
DerivedClass d;
}
Output
DerivedClass destructor
BaseClass2 destructor
BaseClass1 destructor