简体   繁体   中英

protected inheritance

Why protected and private inheritance are defined and proposed? I understand some cases private inheritance could be used but it is not recommended. How about protected inheritance?

Can anyone offer me an situation in which protected inheritance is a choice?

I rarely see this.

Thanks so much!

Private inheritance is usually used for mixins---where people inherit to get functionality from the base class, rather than because of "is-a" inheritance.

Protected inheritance can also be used for mixins, where the mixed-in functionality is to be available to downstream classes too.

I generally don't use protected inheritance. In fact, I don't generally use private inheritance. If something does not satisfy the Liskov Substitution Principle then I don't see a reason to use inheritance of any kind; and if it does satisfy LSP then you use public inheritance.

However, the language distinguishes between private and protected only from the class's point of view (that is, code using the class can't tell the difference).

You should use protected inheritance when you want it's semantics , and you should use private when you don't want protected .

请参阅Herb Sutter的继承和滥用继承,第1部分 ,这也是他更加特殊的C ++书籍。

This is a situation i would use Protected inheritance

Base -> Derived1 -> Derived2

  • I dont want Derived1 to be substituted for the Base class
  • I want to use functionality in base and also allow the Derived2 to use it without exposing the functionality to client classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM