Search code examples
c++abstract-classvirtual-functionsprivate-inheritance

does it make sense to inherit privately from an abstract (pure virtual) class?


suppose this construct

struct InterfaceForFoo
{
    virtual void GetItDone() = 0;
};


class APoliticallyCorrectImplementationOfFooRelatedThings : private InterfaceForFoo
{

  public:
    void GetItDone() { /*do the thing already*/ };   
};

Now, i'm wondering if inheriting privately from an interface in this way do have any useful scenarios.


Solution

  • Huh, everyone here says "no". I say "yes, it does make sense."

    class VirtualBase {
    public:
        virtual void vmethod() = 0;
        // If "global" is an instance of Concrete, then you can still access
        // VirtualBase's public members, even though they're private members for Concrete
        static VirtualBase *global;
    };
    
    // This can also access all of VirtualBase's public members,
    // even if an instance of Concrete is passed in,
    void someComplicatedFunction(VirtualBase &obj, ...);
    
    class Concrete : private VirtualBase {
    private:
        virtual void vmethod();
    public:
        void cmethod() {
            // This assignment can only be done by Concrete or friends of Concrete
            VirtualBase::global = this;
            // This can also only be done by Concrete and friends
            someComplicatedFunction(*this);
        }
    };
    

    Making inheritance private doesn't mean that you can't access the members of VirtualBase from outside the class, it only means that you can't access those members through a reference to Concrete. However, Concrete and its friends can cast instances of Concrete to VirtualBase, and then anybody can access public members. Simply,

    Concrete *obj = new Concrete;
    obj->vmethod(); // error, vmethod is private
    
    VirtualBase *obj = VirtualBase::global;
    obj->vmethod(); // OK, even if "obj" is really an instance of Concrete