C++ “virtual” keyword for functions in derived classes. Is it necessary?

后端 未结 9 1416
遇见更好的自我
遇见更好的自我 2020-11-22 15:17

With the struct definition given below...

struct A {
    virtual void hello() = 0;
};

Approach #1:

struct B : public A {
           


        
相关标签:
9条回答
  • 2020-11-22 15:49

    The virtual keyword is not necessary in the derived class. Here's the supporting documentation, from the C++ Draft Standard (N3337) (emphasis mine):

    10.3 Virtual functions

    2 If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

    0 讨论(0)
  • 2020-11-22 15:49

    No, the virtual keyword on derived classes' virtual function overrides is not required. But it is worth mentioning a related pitfall: a failure to override a virtual function.

    The failure to override occurs if you intend to override a virtual function in a derived class, but make an error in the signature so that it declares a new and different virtual function. This function may be an overload of the base class function, or it might differ in name. Whether or not you use the virtual keyword in the derived class function declaration, the compiler would not be able to tell that you intended to override a function from a base class.

    This pitfall is, however, thankfully addressed by the C++11 explicit override language feature, which allows the source code to clearly specify that a member function is intended to override a base class function:

    struct Base {
        virtual void some_func(float);
    };
    
    struct Derived : Base {
        virtual void some_func(int) override; // ill-formed - doesn't override a base class method
    };
    

    The compiler will issue a compile-time error and the programming error will be immediately obvious (perhaps the function in Derived should have taken a float as the argument).

    Refer to WP:C++11.

    0 讨论(0)
  • 2020-11-22 15:50

    There is no difference for the compiler, when you write the virtual in the derived class or omit it.

    But you need to look at the base class to get this information. Therfore I would recommend to add the virtual keyword also in the derived class, if you want to show to the human that this function is virtual.

    0 讨论(0)
提交回复
热议问题