Why is 'virtual' optional for overridden methods in derived classes?

前端 未结 5 1819
走了就别回头了
走了就别回头了 2021-02-05 12:53

When a method is declared as virtual in a class, its overrides in derived classes are automatically considered virtual as well, and the C++ language ma

5条回答
  •  长情又很酷
    2021-02-05 13:28

    As a related note, in C++0x you have the option of enforcing being explicit with your overrides via the new attribute syntax.

    struct Base {
      virtual void Virtual();
      void NonVirtual();
    };
    
    struct Derived [[base_check]] : Base {
      //void Virtual(); //Error; didn't specify that you were overriding
      void Virtual [[override]](); //Not an error
      //void NonVirtual [[override]](); //Error; not virtual in Base
      //virtual void SomeRandomFunction [[override]](); //Error, doesn't exist in Base
    };
    

    You can also specify when you intend to hide a member via the [[hiding]] attribute. It makes your code somewhat more verbose, but it can catch a lot of annoying bugs at compile time, like if you did void Vritual() instead of void Virtual() and ended up introducing a whole new function when you meant to override an existing one.

提交回复
热议问题