protected inheritance

前端 未结 4 1446
眼角桃花
眼角桃花 2021-01-11 19:30

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 inhe

相关标签:
4条回答
  • 2021-01-11 20:03

    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
    0 讨论(0)
  • 2021-01-11 20:08

    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.

    0 讨论(0)
  • 2021-01-11 20:20

    See Herb Sutter's Uses and Abuses of Inheritance, Part 1, which is also in his More Exceptional C++ book.

    0 讨论(0)
  • 2021-01-11 20:25

    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.

    0 讨论(0)
提交回复
热议问题