randomThought
randomThought

Reputation: 6393

multi class inheritance setup issues

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

Upvotes: 0

Views: 46

Answers (1)

George Hilliard
George Hilliard

Reputation: 15952

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.

Upvotes: 1

Related Questions