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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值