4/23/08

Explain use of Private Inheritance

The use of public inheritance implies an is-a relationship between a base class and its descendant. Unlike public inheritance, private inheritance is used when you want to inherit the implementation of the base class without the is-a commitment. Thus, if A is a non-public base of B, B has access to all the non-private members of A, but it's not an A. In this regard, private inheritance is almost identical to containment. When should you use private inheritance? Suppose you want to create a collection of objects of a certain type while reusing the functionality of another container class, say, Stack. You don't want your derived class D to behave as a Stack, you simply need the implementation of the Stack class. In this case, you privately derive D from Stack:
class Stack
{
public:
void push(Element &);
void pop();
}
class B: private Stack
{
public:
int insert(const Element & e)
{
push(e); // reuse Stack::push
}
};
Note that the use of private inheritance allows you to change the implementation of B::insert transparently. You may decide at a later stage to use a different container instead of Stack without affecting B's users, who have no access to the actual implementation anyway.

No comments:

ITUCU