views:

202

answers:

6

I dont completely understand this:

class Base
{
    public:
    Base()
    {
        cout<<"Base" << endl;
    }

    virtual void call()
    {
        cout<<"Base call" << endl; 
    }
};

class Derived: private Base
{
    public:      
    Derived()
    {
        cout<<"Derived" << endl;
    } 
};

int main(void)
{
    Base *bPtr = new Derived(); // This is not allowed
}

Is it because someone might call call() using bPtr which is actually done on derived object? Or is there any other reason?

A: 

With private inheritance, you loose the option to treat your derived object as an object of your base class.

Maximilian Mayerl
+7  A: 

“Private inheritance” is a horrible misnomer: it is not inheritance (as far as everything outside of the class is concerned). Seen from the outside, private inheritance is actually the same as composition. Only on the inside of the class do you get special syntax that is more reminiscent of inheritance than composition.

Konrad Rudolph
It's implementation inheritance rather than interface inheritance.
Laurence Gonsalves
@Laurence: true, but that’s just arguing terminology. I was concerned with the outside view on the class.
Konrad Rudolph
And it's allowed with c-style casts to actually do `Base *bPtr = (Base*)new Derived();` portably with defined behavior. No C++ style cast has this power.
Johannes Schaub - litb
+1  A: 

If you inherit privately any code that requires the conversion from Derived* to Base* must be a member or a friend of the Derived class.

sellibitze
Thanks for the answers, but i actually wanted to know why did they not allow this to happen.
nitin soman
+2  A: 

Because private means "implementation detail", which makes the fact that Derived derives from Base an implementation detail.

Private inheritance is not interface inheritance, but implementation inheritance. It doesn't implement an "Is-A" relationship, but an "Is-Implemented-Using" relationship. Derived isn't a Base as far as users of the classes are concerned, it just happens to (currently) be implemented using it.

sbi
+2  A: 

Public inheritance means that everyone knows that Derived is derived from Base.

Protected inheritance means that only Derived, friends of Derived, and classes derived from Derived know that Derived is derived from Base.*

Private inheritance means that only Derived and friends of Derived know that Derived is derived from Base.

Since you have used private inheritance, your main() function has no clue about the derivation from base, hence can't assign the pointer.

Private inheritance is usually used to fulfill the "is-implemented-in-terms-of" relationship. One example might be that Base exposes a virtual function that you need to override -- and thus must be inherited from -- but you don't want clients to know that you have that inheritance relationship.

*also: how much wood would a woodchuck chuck...

Kaz Dragon