Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c++ - Private inheritance VS composition : when to use which?

Private inheritance VS composition.

I'm having a little confusion when to use each. Since private inheritance seals, in a way, the chain on inheritance, given:

class A
{
private:
    int z;
protected:
    int y;
public:
    int x;
};

class B : private A
{
    /* B's data members and methods */
    /* B has access only to A's public and protected */
};

class C : public B
{
    /* can access no fields of B */
};

C won't be able to use any of B's fields. When would I use private inheritance, and when would I use composition?

thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()
";
     }
 };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...