Private inheritance VS composition : when to use which?

前端 未结 1 530
半阙折子戏
半阙折子戏 2020-11-30 11:27

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:

相关标签:
1条回答
  • 2020-11-30 11:55

    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()\n";
           wilmaCallsFred();
         }
       virtual void wilmaCallsFred() = 0;   // A pure virtual function
     };
    
     class Fred : private Wilma {
     public:
       void barney()
         {
           std::cout << "Fred::barney()\n";
           Wilma::fredCallsWilma();
         }
     protected:
       virtual void wilmaCallsFred()
         {
           std::cout << "Fred::wilmaCallsFred()\n";
         }
     };
    
    0 讨论(0)
提交回复
热议问题