This C++ FAQ entry answers your questions aptly.
Replicating it here:
Use composition when you can, private inheritance when you have to.
Normally you don't want to have access to the internals of too many other classes, and private inheritance gives you some of this extra power (and responsibility). But private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code.
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.
class Wilma {
protected:
void fredCallsWilma()
{
std::cout << "Wilma::fredCallsWilma()
";
wilmaCallsFred();
}
virtual void wilmaCallsFred() = 0; // A pure virtual function
};
class Fred : private Wilma {
public:
void barney()
{
std::cout << "Fred::barney()
";
Wilma::fredCallsWilma();
}
protected:
virtual void wilmaCallsFred()
{
std::cout << "Fred::wilmaCallsFred()
";
}
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…