nonpublic over containment

That being the case, what are the extra things we can do if we use inheritance that we can't do if we
use containment? In other words, why use nonpublic inheritance? Here are several reasons, in rough
order from most to least common. Interestingly, the final item points out a useful(?) application of
protected inheritance.
We need to override a virtual function. This is one of inheritance's classic raisons d'être. [7]
Often, we want to override in order to customize the used class's behavior. Sometimes,
however, there's no other choice. If the used class is abstract—that is, it has at least one pure
virtual function that has not yet been overridden—we must inherit and override because we
can't instantiate directly.
[7] See also Meyers98 under the index entry, "French, gratuitous use of."
We need access to a protected member. This applies to protected member functions[8] in
general, and to protected constructors in particular.

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 by using inheritance.
This can be necessary when the used class provides a lock of some sort, such as a critical
section or a database transaction, which must cover the entire lifetime of another base
subobject.
We need to share a common virtual base class or override the construction of a virtual base
class. The first part applies if the using class has to inherit from one of the same virtual bases as
the used class. If it does not, the second part may still apply. The most-derived class is
responsible for initializing all virtual base classes, so if we need to use a different constructor or
different constructor parameters for a virtual base, then we must inherit.
We benefit substantially from the empty base class optimization. Sometimes, the class you are
IMPLEMENTING-IN-TERMS-OF may have no data members at all—that is, it's just a bundle of
functions. In this case, there can be a space advantage to using inheritance instead of
containment because of the empty base class optimization. In short, compilers are allowed to let
an empty base subobject occupy zero space; whereas an empty member object must occupy
nonzero space, even if it doesn't have any data.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章