While explaining when private inheritance must be used, instead of containment, the author of this article says the following :
“We need to construct the used object before, or destroy it after, another base subobject. If the slightly longer object lifetime matters, there’s no way to get it other than using inheritance”
If you want subobject A to be constructed before subobject B and destructed after B, wouldn’t be enough to declare A before B, in the enclosing class ? In other words, why can’t we use containment to achieve the same result in this case ?
I believe that the author is talking about base subobjects, not direct subobjects. That is, you would use private inheritance if you wanted some member of the class to be constructed before the class’s other base classes would be constructed. In this case, using private inheritance will cause C++ to initialize the privately-inherited base class before other base classes, provided that you’ve inherited from them in the right order. For example, if you’re making class
Derived, want aSubobjectobject inDerived, and inherit fromBase, but you want theSubobjectinitialized before theBase, you could writeAnd now the
Subobjectwill be initialized before theBase.(That said, this is a pretty silly use case!)
Hope this helps!