I have a question based on this question
In the section http://www.parashift.com/c%2B%2B-faq-lite/private-inheritance.html#faq-24.3 the following is mentioned:
A legitimate, long-term use for private inheritance is when you want to build a class Fred that uses code in a class Wilma, and the code from class Wilma needs to invoke member functions from your new class, Fred. In this case, Fred calls non-virtuals in Wilma, and Wilma calls (usually pure virtuals) in itself, which are overridden by Fred. This would be much harder to do with composition.
However, I would like to know why using public inheritence would not achieve the same effect. i.e the following piece of c# code does the same thing..
class Wilma
{
protected void FredCallsWilma() {
Console.Write("Fred Calls Wilma ;");
WilmaCallsFred();
}
protected virtual void WilmaCallsFred() {}
}
class Fred : Wilma
{
public void barney(){
Console.Write("barney;");
FredC开发者_JS百科allsWilma();
}
protected override void WilmaCallsFred(){
Console.Write("Wilma Calls Fred ;");
}
}
class Program
{
static void Main(string[] args){
Fred f1 = new Fred();
f1.barney();
}
}
It prints
barney; Fred Calls Wilma ; Wilma Calls Fred
So what is special about private inheritence as quoted in the c++ faq lite. Would not substituting public inheritence for private inheritence work just fine to achieve that result?
Public inheritance makes the base class accessible to the outside world. For example, a pointer to the derived class can be converted (implicitly, no less) to a pointer to the base class. Consider a stack that's derived from a linked list. You generally would NOT want somebody implicitly converting your array to its base linked list, which would allow them to do things not allowed for a stack, such as inserting or deleting items in the middle.
The usual meaning attributed to private inheritance is "Is implemented in terms of" -- which means we normally do NOT want to allow the outside world/user to see/know/care about the fact that this class has a base class. Public inheritance should follow the Liskov substitution rule, which says that a derived class can be substituted anywhere a public base class is called for. With private inheritance, we're specifically NOT saying that the derived class can be substituted for the base class.
Public inheritance is a design technique. Its intent is to allow the code you're writing to be used by other code that already knows how to work with the interface presented by the base class.
Private inheritance is an implementation technique. Its intent is only to simplify your implementation by using code from the base class.
Yes, you are correct. The quoted paragraph is only quoting that child classes have access to private members of inhereted classes, and a possible use case for that.
Some people incorrectly assume that you can't access private members of inherited classes.
精彩评论