4

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?

2
  • In this case there's no need to inherit ClassInherit from InterfaceInherited again. It already inherits that interface from ClassBase. Commented Jan 4, 2021 at 8:49
  • The fact is that it is inheriting from both ClassBase and from InterfaceInherited, but the last one has not defined the SomeMethod implementation, so that one is still pending in ClassInherited; this makes ClassInherited abstract so is not instatiable. Commented Jan 4, 2021 at 9:03

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It would be good if you cleaned it up a little bit too. Increase indentation and remove some lines. There's no reason that this should require scrolling. See my edit of OP:s post.
Some compilers will warn you about this inheritance structure. These warnings can be ignored or silenced.

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.