Overriding public virtual functions with private functions in C++

前端 未结 7 621
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 02:51

Is there is any reason to make the permissions on an overridden C++ virtual function different from the base class? Is there any danger in doing so?

For example:

7条回答
  •  孤街浪徒
    2020-11-27 03:25

    A good use-case for private inheritance is a Listener/Observer event interface.

    Example code for the private object:

    class AnimatableListener {
      public:
        virtual void Animate(float delta_time);
    };
    
    class BouncyBall : public AnimatableListener {
      public:
        void TossUp() {}
      private:
        void Animate(float delta_time) override { }
    };
    

    Some users of the object want the parent functionality and some want the child functionality:

    class AnimationList {
       public:
         void AnimateAll() {
           for (auto & animatable : animatables) {
             // Uses the parent functionality.
             animatable->Animate();
           }
         }
       private:
         vector animatables;
    };
    
    class Seal {
      public:
        void Dance() {
          // Uses unique functionality.
          ball->TossUp();
        }
      private:
        BouncyBall* ball;
    };
    

    This way the AnimationList can hold a reference to the parents and uses parent functionality. While the Seal holds a reference to the child and uses the unique child functionality and ignoring the parent's. In this example, the Seal shouldn't call Animate. Now, as mentioned above, Animate can be called by casting to the base object, but that's more difficult and generally shouldn't be done.

提交回复
热议问题