Inheritance with interfaces

Viewed 148

I'm currently trying to wrap my head around the basics of C++ inheritance. Consider the following piece of code:

// Interfaces

class InterfaceBase
{
public:
    virtual void SomeMethod() = 0;
};

class InterfaceInherited : public InterfaceBase
{
};

// Classes

class ClassBase : public InterfaceBase
{
public:
    virtual void SomeMethod()
    {
    }
};

class ClassInherited : public ClassBase, public InterfaceInherited
{
};

int main()
{
    ClassBase myBase; // OK
    ClassInherited myInherited; // Error on this line

  return 0;
}

Here I have two interfaces with an inheritance relationship. The same goes for the two classes which implement the interfaces.

This gives me the following compiler error:

C2259 'ClassInherited': cannot instantiate abstract class

It seems that the class ClassInherited does not inherit the implementation of SomeMethod from ClassBase. Thus it is abstract and cannot be instantiated.

How would I need to modify this simple example in order to let ClassInherited inherit all the implemented methods from ClassBase?

1 Answers

You are encountering a diamond problem. The solution is to use virtual inheritance (Live), to ensure that only one copy of base class members are inherited by grand-childs:

// Interfaces
class InterfaceBase
{
public:
    virtual void SomeMethod() = 0;
};

class InterfaceInherited : virtual public InterfaceBase
{
};

// Classes
class ClassBase : virtual public  InterfaceBase
{
public:
    virtual void SomeMethod()
    {
    }
};

class ClassInherited : public ClassBase, public InterfaceInherited
{
};

int main()
{
    ClassBase myBase; // OK
    ClassInherited myInherited; // OK
    return 0;
}
Related