In C++ we have another great feature called inheritance. Inheritance is the derived class that can acquire the features of a base class.
Multiple inheritance:
A class that can inherit from more than one class is called multiple inheritance. In multiple inheritance, the order of constructor calls is the order that they are inherited.
Let us see the below example that helps us to understand the order of constructors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include <iostream> using namespace std; #define CLASS(ID) class ID { \ public: \ ID(int) { cout << #ID " constructor" << endl; } \ ~ID() { cout << #ID " destructor" << endl; } \ }; CLASS(Base1); CLASS(Derived_1); CLASS(Derived_2); CLASS(Derived_3); CLASS(Derived_4); class MyDerived1 : public Base1 { Derived_1 m1; Derived_2 m2; public: MyDerived1(int) : m2(1), m1(2), Base1(3) { cout << "MyDerived1 constructor" << endl; } ~MyDerived1() { cout << "MyDerived1 destructor" << endl; } }; class MyDerived2 : public MyDerived1 { Derived_3 m3; Derived_4 m4; public: MyDerived2() : m3(1), MyDerived1(2), m4(3) { cout << "MyDerived2 constructor" << endl; } ~MyDerived2 () { cout << "MyDerived2 destructor" << endl; } }; int main() { MyDerived2 *d2 = new MyDerived2; delete d2; d2 = NULL; getchar (); return 0; } |
Output of the above program is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Base1 constructor Derived_1 constructor Derived_2 constructor MyDerived1 constructor Derived_3 constructor Derived_4 constructor MyDerived2 constructor MyDerived2 destructor Derived_4 destructor Derived_3 destructor MyDerived1 destructor Derived_2 destructor Derived_1 destructor Base1 destructor |
The destructors are called in reverse order of constructors.
Explanation:
We can observe that the calling of the constructer starts at the base class.
So each level the base class constructor is called first, followed by the member object constructors.
Coming to the story of destructors which are called in exactly the reverse order of the constructors – this is important because of potential dependencies.