It's difficult to come up with a simple example because the instances in which you would use protected and private inheritance are more complex. In simple situations, you're better off avoiding them completely.
Public inheritance implies an "is a" relationship. If
Poodle
is (publically) derived from
Dog
, then a Poodle "is a" Dog.
Protected/Private inheritance change this relationship to more of a "has a" relationship. If
Computer
is privately derived from
Motherboard
then a Computer "has a" Motherboard. The thing is, it's much easier (and safer) to form a "has a" relationship by simply making Motherboard a member of Computer, rather than deriving from it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class Motherboard {};
// this makes a "has a" relationship
class Computer : private Motherboard
{
};
// this makes a similar "has a" relationship
// this approach is aka "composition"
class Computer
{
private:
Motherboard mobo;
};
|
One advantage to using protected/private inheritance instead of composition is that the derived class has access to protected members in the parent class. However this is kind of a double-edged sword, as it becomes easier to misuse the class.
Another advantage is the parent class can more easily call functions in the derived class by way of virtual functions. This allows for a sort of "two way" communication between classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class Parent
{
public:
virtual void CallChild() = 0;
void DoStuff()
{
CallChild(); // calls a function in the child class
}
};
class Child : private Parent
{
public:
virtual void CallChild() { /*...*/ }
};
|
This sort of relationship is a bit harder (but not impossible) to accomplish with the composition approach.
Protected/private inheritance isn't used that often. I can't recall a time when I had to use it.