c++inheritancemultiple-inheritancepure-virtualprivate-inheritance

How can I override a pure virtual method using a privately inherited method?


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?


Solution

  • 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