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

前端 未结 5 1817
走了就别回头了
走了就别回头了 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:43

    Yeah, it would really be nicer to make the compiler enforce the virtual in this case, and I agree that this is a error in design that is maintained for backwards compatibility.

    However there's one trick that would be impossible without it:

    class NonVirtualBase {
      void func() {};
    };
    
    class VirtualBase {
      virtual void func() = 0;
    };
    
    template
    class CompileTimeVirtualityChoice : public VirtualChoice {
      void func() {}
    };
    

    With the above we have compile time choice wether we want virtuality of func or not:

    CompileTimeVirtualityChoice -- func is virtual
    CompileTimeVirtualityChoice -- func is not virtual
    

    ... but agreed, it's a minor benefit for the cost of seeking a function's virtuality, and myself, I always try to type virtual everywhere where applicable.

提交回复
热议问题