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

1
  • no. public. forgot the keyword there Commented Jun 30, 2014 at 18:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Compiles with clang but vc++ gives warnings that Cimpl inherits M1 by dominance and warnings are treated as errors in my project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.