What does the virtual keyword mean when overriding a method?

前端 未结 4 883
生来不讨喜
生来不讨喜 2021-01-11 12:16

What does the keyword virtual do when overriding a method? I\'m not using it and everything works fine.

Does every compiler behave the same in this

4条回答
  •  孤街浪徒
    2021-01-11 13:02

    A virtual method in the base class will cascade through the hierarchy, making every subclass method with the same signature also virtual.

    class Base{
    public:
      virtual void foo(){}
    };
    
    class Derived1 : public Base{
    public:
      virtual void foo(){} // fine, but 'virtual' is no needed
    };
    
    class Derived2 : public Base{
    public:
      void foo(){} // also fine, implicitly 'virtual'
    };
    

    I'd recommend writing the virtual though, if for documentation purpose only.

提交回复
热议问题