Private inheritance is also easy but pointless
A : private B means A is implemented by B. However, that's pointless because that means A should contain B instead. Ownership means less coupling with no disadvantage.
That you might not see reasons for private inheritance does not mean it's pointless.
There are several cases where private inheritance has it's reasons. You are right in that at a first glance, private inheritance means has-a relationships just like aggregation, and that private inheritance has a (slightly) tighter coupling.
Reasons for favouring private inheritance over aggretations could be some of the following:
- With private inheritance you inherit typedefs as well. In some cases (e.g. traits classes) inheriting privatly is just the alternative to re-typedef tons of typedefs in the base class.
- In seldom cases you have to initialize a member before a "real" (i.e. public) base class. The only way to achieve that is by making that member a private base class inherited before the public base.
- Some times you need access to protected members of a member. If you can't change the member class itself, you have to use private inheritance to get access to them.
- If a member has no data members of its own, it still occupies space. Making it a private base class enables the empty base class optimization, diminuishing the size of your class' objects.
- for even more points, see James' comments below
These reasons are obviously technical reasons, some might even say "hacks". However, such reasons exist, so private inheritance is not completely pointless. It is just not "pure OO style" - but C++ isn't a pure OO language either.
The reason for protected inheritance are quite simple once you understood the ones for private inheritance:
If you have reasons to inherit something privately and want to make those benefits (i.e. that would-be member of your class or the typedefs) accessible to derived classes, use protected inheritance. Obviously, private inheritance should be used scarcely, and protected inheritance even more so.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…