Public and private inheritance in C++

Narek picture Narek · Jan 6, 2011 · Viewed 18.6k times · Source

As we know from the literature for the public inheritance the object of child class (sub-class) also can be considered as the object of base class (super-class). Why the object of the sub-class can’t be considered as an object of super-class, when the inheritance is protected or private?

Answer

Martin York picture Martin York · Jan 6, 2011

Because you can't see it:

class Base
{
    public: virtual ~Base() {}
};

class PublicDerived: public Base
{    };

class PrivateDerived: private Base
{    };

int main()
{
    PublicDerived   publicD;
    PrivateDerived  privateD;

    Base&           base1 = publicD;
    Base&           base2 = privateD; // ERROR
} 

So you can not use a PrivateDerived object where a Base object could be used.
So it will never act like a Base class object.