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?
protected inheritance makes the public and protected members of the base class protected in the derived class. private inheritance makes the public and protected members of the base class private in the derived class.
Private Members in a SuperclassA subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
The private members of a class can be inherited but cannot be accessed directly by its derived classes. They can be accessed using public or protected methods of the base class. The inheritance mode specifies how the protected and public data members are accessible by the derived classes.
The private -inheritance variant allows access to the protected members of the base class. The private -inheritance variant allows Car to override Engine 's virtual functions.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With