Search code examples
c++visual-studiovisual-c++inheritanceprivate

How private inheritance allowed me to create object?


I have simple code, which I assume to be failed.

I have privately inherit Shield from Sealer, and even Shield is not it's friend, still I am able to create object of Shield.

class Sealer
{
public:

    Sealer()
    {
        cout<<"base constructor;"<<endl;
    }

};

class Shield : private Sealer
{
public:

    void p()
    {
        cout<<"P gets called;"<<endl;
    }
};

int main()                          
{
    Shield d;  //success here
    d.p(); // here too
    return 0;
}

How it is possible? Base class constructor should not be accessible. Isn't it?

I am using Visual Studio 2012.


Solution

  • class Shield : private Sealer means that everything in Sealer is kept private within Shield; it cannot be seen outside Shield or in classes derived from it.

    It does not magically go back and make Sealer's constructor private so that Shield cannot access it. What would be the point of private inheritance if the child class could not access anything from the base class? It would do exactly nothing.