Question

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 ?

Was it helpful?

Solution

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 a Subobject object in Derived, and inherit from Base, but you want the Subobject initialized before the Base, you could write

class Derived: private Subobject, public Base {

}

And now the Subobject will be initialized before the Base.

(That said, this is a pretty silly use case!)

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top