Thursday, 27 November 2014

Multiple Inheritance with examples in C++

Multiple Inheritance with examples in C++:

In C++ we have another great feature called inheritance. Inheritance is the derived class can acquire the features of base class.

Multiple inheritance:

A class that can inherit from more than one class is called as multiple inheritance.

In multiple inheritance the order of constructor calling is the order that they are inherited.

Let us see the below example that helps us to understand the order of constructors.
#include <iostream>
using namespace std;
#define CLASS(ID) class ID { \
public: \
ID(int) { cout << #ID " constructor" << endl; } \
~ID() { cout << #ID " destructor" << endl; } \
class MyDerived1 : public Base1
Derived_1 m1;
Derived_2 m2;
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;
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:
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.

We can observe that the calling of the constructer starts at the base class.
So the 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.

You can find more information on Diamond Problem .

No comments: