Isn't 'virtual' keyword redundant when

2019-07-12 03:31发布

问题:

Let's say I have the following base class:

class Base {
    public:
        virtual void f() {};
};

If I want to write a class that will override the f() and will not allow to override it to it's derived classes can write it using following approaches:

Approach 1:

class Derived : public Base {
    public:
        virtual void f() override final {};
};

Approach 2:

class Derived : public Base {
    public:
        void f() final {};
};

Approach 1 is a fully detailed when Approach 2 more compact and final still says that f() is actually virtual and overrides the base class method.

Which one approach is more appropriate?

回答1:

In "Approach 1", the virtual is indeed redundant. 'override' is a special identifier that shows the reader of the code that a virtual function is being overridden, while also being a hint for the compiler to verify that it actually is. The base class has already stated that the function is virtual, so there is no need to do that again.

When not using the 'final' keyword, it is good practice to have a 'virtual', simply to maintain readability. Approach 2 is the best-practice notation in this case.

This kinda comes down to the style that is used in your environment, but final definitly does not imply override final.



回答2:

class Derived : public Base {
public:
    void f() override final {};
};

Maybe that way? virtual keyword is not needed in derived class, override and final both give you a compiler error if there is no method to override, but you or someone else may want to remove final keyword in future then override give you a pure intention of your method behavior.