Search code examples
c++polymorphismvirtualmultiple-inheritanceabstract

Multiple inheritance conflict


I have the following code:

class Interface
{
  virtual void method()=0;
};

class Base : public Interface
{
  virtual void method()
  {
    //implementation here
  }
};

class Parent: public Interface
{

};

class Child : public Base, public Parent
{

};

int main()
{
  Child c;//ERROR: cannot instantiate abstract class
}

Now I know why this is happening, since I'm inheriting Parent then I have to implement method again. But it's already defined in Base class and I don't want to override that definition for every child class. I think there was some standard way of getting rid of this in c++ (telling compiler which copy of Interface should it use) I just can't remember what it was.


Solution

  • You have a diamond-shaped hierarchy but are not using virtual inheritance.

    As a result, you end up with two distinct virtual method() functions in your Child class.

    One way to fix it is to move to using virtual inheritance. This way you'll only have a single Child::method() and won't need two implementations.