tags:

views:

244

answers:

4

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!

+5  A: 

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.

Chris Jester-Young
can you give me an example of protected inheritance, for example, for private inheritance, car private inherited from engine is usually used.
skydoor
+1. That is I think the only use for protected inheritance.
Nikolai N Fetissov
Car `has-a` engine. So ideally `composition` should be used and not `inheritance`. Generally one should use inheritance when the relationship is `is-a`. Just my 2 cents.
Gautam Borad
@Gautam: While in many cases composition is more ideal for has-a, in some cases, non-public inheritance can be used instead. Of course, public inheritance must model is-a.
Chris Jester-Young
+2  A: 

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.

Max Lybbert
If something uses private inheritance, then from the POV of non-friends, it doesn't inherit from the base and hence certainly doesn't satisfy LSP. Private inheritance is for when the inheritance is an implementation detail, not part of the public interface. So perhaps it *could* satisfy LSP, perhaps not, but either way you don't want it to.
Steve Jessop
+2  A: 

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

Nikolai N Fetissov
A: 

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
Yogesh Arora