2

I have the following:

class Abstract
{
    virtual void AbstractMethod() = 0;
};

class Implementer
{
    void AbstractMethod() {};
};

class Concrete : public Abstract, private Implementer
{};

I cannot instantiate Concrete because the pure virtual method AbstractMethod is not overridden. What am I doing wrong?

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
Dan Nestor
  • 2,441
  • 1
  • 24
  • 45

1 Answers1

6

You are using multiple inheritance here.

Concrete has two hierarchies treated separately:

Abstract and Implementer. Since Abstract has no relation to Implementer your use of virtual in that case (for sibling inheritance) will fail.

You need to override virtual functions in derived classes. You cannot do it in the manner you are attempting.

Specifically, if you were to re-write it as such it would work:

class Abstract
{
    virtual void AbstractMethod() = 0;
};

class Implementer : private Abstract
{
    void AbstractMethod() {};
};

class Concrete : public Implementer
{};

I would like to point out your use of public or private inheritance in Concrete does not affect the problem. If you change Implementer to public in your original example it would still fail to be a concrete class.

Useful Auxiliary Information: Avoid multiple inheritance when possible, favor composition over inheritance, and prefer shallow inheritance over deep. http://en.wikipedia.org/wiki/Composition_over_inheritance

If you are going through the route of multiple inheritance be aware of separate inheritance hierarchies being default in C++, and the need for virtual inheritance to combine the different paths (virtual methods still require a derived class to override them, not sibling classes though): http://en.wikipedia.org/wiki/Multiple_inheritance

M2tM
  • 4,415
  • 1
  • 34
  • 43
  • So the two hierarchies cannot somehow be "unified" in `Concrete`, in any way? – Dan Nestor Jun 30 '14 at 22:07
  • @Deduplicator - I could also not write the program, that would also get rid of the error ;) – Dan Nestor Jun 30 '14 at 22:08
  • @DanNestor you can use virtual inheritance to avoid multiple hierarchies that share a common base class, but no, not in the way you desire for virtual method overrides. – M2tM Jun 30 '14 at 22:09
  • @DanNestor it is also best to limit your use of multiple inheritance wherever possible. Multiple inheritance of abstract base classes is relatively harmless (and can be useful for specifying interfaces similar to Java/C# from what I am aware) but it can get quite complicated when you have shared state. This is just a word of caution. Favor composition and shallow inheritance over deep and branching polymorphism where possible. A good read: http://en.wikipedia.org/wiki/Composition_over_inheritance – M2tM Jun 30 '14 at 22:13