Use cases for final classes

后端 未结 2 968
囚心锁ツ
囚心锁ツ 2020-12-16 11:37

I was reading comments on Herb Sutter\'s Guru of the Week redux about virtual functions, and finally saw him mentioning this:

[...] “uses

2条回答
  •  抹茶落季
    2020-12-16 11:48

    final might be useful when you provide a (sort of) facade to the initial interface, which is easier to use by subclasses. Consider:

    class IMovable {
      public:
        void GoTo(unsigned position) = 0;
    }
    
    class Stepper : public IMovable {
      public:
        void GoTo(unsigned position) final;
      protected:
        virtual void MoveLeft() = 0;
        virtual void MoveRight() = 0;
    }
    
    void Stepper::GoTo(unsigned position) {
      for(;current_pos < position; current_pos++) {
         MoveRight(); 
      }
      for(;current_pos > position; current_pos--) {
         MoveLeft();
      } 
    }       
    

    Now if you want to derive from Stepper you see that you should override MoveRight and MoveLeft, but you shouldn't override GoTo.

    It is obvious on this small example, but if IMovable had 20 methods and Stepper had 25, and there were default implementations, than you might have hard time figuring out what you should and what you shouldn't override. I have met a situation like this in a hardware-related library. But I wouldn't call this a major problem worth adressing by the standard;)

提交回复
热议问题