C++ Multipath inheritance

Multipath inheritance in C++ is derivation of a class from other derived classes, which are derived from the same base class. In this type of inheritance,  there involves other inheritance like multiple, multilevel, hierarchical etc.

It is famously known as diamond problem in computer programming.

multipath-inheri

Figure: Multipath inheritance

  • Here, class D is derived from derived classes B & C directly and from class A indirectly. (hierarchical and multiple)
  • Both derived classes inherits the features of base class. Hence when we derive a new class by inheriting features form these two classes derived from the same base class, then same features from the first base is inherited to the finally derived class from two paths. This cause ambiguity in accessing first base class members.
//example of multipath inheritance
//ambiguous base class member access
class A
{
private: //..
public:
    void showdata()
    {
        //...
    }
};
class B: virtual public A
{
    //...
};
class C: virtual public A
{
    //..
};
class D: public B, public C
{
public:
    void show_data()
    {
        showdata();//ambiguous which showdata() ?
    }
};
  • To eliminate this problem, C++ has a mechanism to inherit a single copy of properties from the common base class.
  • This is done by declaring the base class as virtual while creating derive classes from this base class.
//example of multipath inheritance
//removing ambiguity with virtual base class
class A
{
private: //..
public:
    void showdata()
    {
        //...
    }
};
class B: virtual public A
{
    //...
};
class C: virtual public A
{
    //..
};
class D: public B, public C
{
public:
    void show_data()
    {
        showdata();//ambiguous which showdata() ?
    }
};

The ambiguity can be resolved without making virtual base class as:

//example of multipath inheritance
//ambiguous base class member access
class A
{
private: //..
public:
    void showdata()
    {
        //...
    }
};
class B: virtual public A
{
    //...
};
class C: virtual public A
{
    //..
};
class D: public B, public C
{
public:
    void show_data()
    {
        showdata();//ambiguous which showdata()
        A::showdata();//still ambiguous because B and C both have A::showdata();
        B::showdata(); //ok, not ambiguous
        C::showdata(); //ok
    }
};

C++ Inheritance Types
Constructor and Destructor in Inheritance