Search code examples
c++inheritancemultiple-inheritance

Multiple inheritance from multiple inheritance


#include<iostream>
using namespace std;

class base1{
public:
    int x;
};
class base2{
public:
    int x;
};

class derived1: public base1, public base2{
    // Contains...  base1::x, base2::x
};
class derived2: public base1, public base2{
    // Contains...  base1::x, base2::x 
};

class derived: public derived1, public derived2{

};

If I am right, the class derived will contain four integers. But I can't access them with
derived1::base1::x, derived1::base2::x, derived2::base1::x, derived2::base2::x


It shows ambiguity error. ('base1' is ambiguous base of 'derived')
Am I missing something? How should I resolve this?


Solution

  • Well, when you use the scope resolution operator to disambiguate between members, you don't name a "path" to the member. You instead name, however indirectly, the base class where the member comes from.

    Since the class name is injected into the scope of the class, and as a result, into the scope of any class that derives from it, you are just naming base1 and base2 in a verbose manner. I.e. all the following are equivalent for the member access:

    derived d;
    d.base1::x;
    d.derived1::base1::x;
    d.derived1::derived1::base1::base1::x;
    

    That's why the ambiguity occurs. The way to do it, is to cast the object into a derived1& or derived2&, and then use member access via base1::x and base2::x on that.

    static_cast<derived1&>(d).base1::x;