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

后端 未结 9 1526
遇见更好的自我
遇见更好的自我 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

    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.

提交回复
热议问题