Search code examples
c++inheritancescopemultiple-inheritance

Access member of non-virtual base class inherited from two different classes


In a multiple derived class whose base classes inherit from the same base class and both the base classes define a member with same name as one in their base class, how to access the member via different path?

The title is quite long, here's an illustration.

struct A{int i;};
struct B1:A{int i;};//non virtual
struct B2:A{int i;};//non vitual
struct C:B1,B2{};

Now how to access the i in A in B1 or i in A in B1 in a C object?

To be clearer, c.i is of course ambiguous, where c is a C. But c.A::i is also ambiguous, there are two viable paths:

C -> B1 -> A
C -> B2 -> A

How do I specify one to use?


Solution

  • static_cast is a verbose, but explicit approach:

    C c;
    static_cast<B1&>(c).i;
    static_cast<B2&>(c).i;
    static_cast<A&>(static_cast<B1&>(c)).i;
    static_cast<A&>(static_cast<B2&>(c)).i;