3

This is the simplified code:

class a
{
public:
    void func( void )
    {
        //Want to call this
    }
    int avar;
};

class b : public a
{
public:
    void func( void )
    {
    }
};

class c : public a
{
public:
    void func( void )
    {
    }
};

class d : public b, public c
{
public:
    void d1()
    {
        //b::a::avar;
        //c::a::avar;
        //b::a::func();
        //c::a::func();
    }
};

How do you properly qualify a call to access the members of both instances of the subclass a, the things I've tried leads to a 'a is an ambiguous base of d' error. Same question if the hierarchy was one more class deep or if a class template was involved. I'm not looking for a virtual base.

  • This is known as diamond inheritance problem. check [link](http://stackoverflow.com/questions/379053/diamond-inheritance-c) and [link](http://www.cprogramming.com/tutorial/virtual_inheritance.html) – Rakib May 02 '14 at 22:05
  • Not in a place to try it, but how about `((c*)this)->avar`? – dlf May 02 '14 at 22:05

1 Answers1

3

You can call the immediate base class functions using the explicit calls.

void d1()
{
    b::func();
    c::func();
}

You can call a::func from b::func similarly.

class b : public a
{
public:
    void func( void )
    {
       a::func();
    }
};

If you also want to access the member a::var and call a::func directly from d::d1, you can use:

void d1()
{
    b* bPtr = this;
    bPtr->avar;        // Access the avar from the b side of the inheritance.
    bPtr->a::func();   // Call a::func() from the b side of the inheritance

    c* cPtr = this;
    cPtr->avar;        // Access the avar from the c side of the inheritance.
    cPtr->a::func();   // Call a::func() from the c side of the inheritance
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270