Private inheritance

I do not quite 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 can call call () using bPtr, which is actually executed on the derived object? Or is there another reason?

+7
c ++ inheritance
source share
6 answers

From a general understanding of C ++ inheritance, “private inheritance” is a terrible misnomer: it’s not inheritance (as far as outside the class is concerned), but the full implementation detail of this class.

It can be seen from the side, private inheritance is actually almost the same as the composition. Only inside the class do you get special syntax that looks more like inheritance than composition.

However, this is a caveat: C ++ treats this syntactically as inheritance, with all the benefits and problems that come with it, such as visibility and scope . In addition, C-style casts (but not C ++ cast!) Actually ignores visibility and thus succeeds in pointing the Derived pointer to Base :

 Base* bPtr = (Base*) new Derived(); 

Needless to say, this is evil .

+18
source share

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

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

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

Since you used private inheritance, your main () function has no idea about generating from the database, therefore it cannot assign a pointer.

Private inheritance is typically used to fulfill the is-implement-in-terms-of relationship. One example might be that Base provides a virtual function that you need to override, and therefore it should be inherited, but you don't want clients to know that you have these inheritance relationships.

* also: how much wood would be a wooden patron ...

+17
source share

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

Private inheritance is not interface inheritance, but implementation inheritance. It does not fulfill the Is-A relationship, but Is-Implemented-Using. Derived not Base in relation to users of classes, it just happens (at present) with its use.

+9
source share

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

+1
source share
+1
source share

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

0
source share

All Articles