0

I have 3 interface (pure virtual) classes like this

class A {
    virtual void M1() = 0;
    virtual void M2() = 0;
};

class B : public A {
    virtual void M3() = 0;
};

class C : public A {
    virtual void M4() = 0;
};

I have the implementers like this

class Aimpl : A {
    void M1 () override {};
    void M2 () override {};
}

class Bimpl: public Aimpl, public B{
     void M3() override {};
}

class Cimpl: public Aimpl, public C{
     void M4() override {};
}

and

Bimpl b = Bimpl();
b.M2() // Error. M2 is ambigous. Can be from Aimpl or A

what's a simple way to fix this? I want to be able to pass around B or C in functions rather than Bimpl

randomThought
  • 6,203
  • 15
  • 56
  • 72

1 Answers1

1

Essentially, you have two different M2 methods in Bimpl: Aimpl::M2 and B::M2. You have run into the diamond-inheritance problem.

To fix it, you should use virtual inheritance. This question provides a very good overview. Essentially, you should use something like this:

class A {
    virtual void M1() = 0;
    virtual void M2() = 0;
};

class B : public virtual A {
    virtual void M3() = 0;
};

class C : public virtual A {
    virtual void M4() = 0;
};

class Aimpl : public virtual A {
    void M1 () override {};
    void M2 () override {};
};

class Bimpl: public virtual Aimpl, public virtual B {
     void M3() override {};
};

class Cimpl: public virtual Aimpl, public virtual C {
     void M4() override {};
};

Note that I'm not super super familiar with virtual inheritance, so this may or may not be the best way to apply virtual inheritance.

Community
  • 1
  • 1
George Hilliard
  • 15,402
  • 9
  • 58
  • 96
  • 1
    Compiles with clang but vc++ gives warnings that Cimpl inherits M1 by dominance and warnings are treated as errors in my project. – randomThought Jun 30 '14 at 18:29
  • 1
    @randomThought http://stackoverflow.com/questions/6864550/c-inheritance-via-dominance-warning – David G Jun 30 '14 at 18:55