4

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?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Alex
  • 9,891
  • 11
  • 53
  • 87
  • 1
    Possible duplicate of [Is it recommended to explicitly make overriding functions virtual?](https://stackoverflow.com/questions/18765380/is-it-recommended-to-explicitly-make-overriding-functions-virtual) – halfelf Feb 19 '19 at 02:56
  • Duplicate of https://stackoverflow.com/questions/39932391/should-i-use-virtual-override-or-both-keywords – Bruce Adams May 10 '22 at 13:43
  • Does this answer your question? [Should I use virtual, override, or both keywords?](https://stackoverflow.com/questions/39932391/should-i-use-virtual-override-or-both-keywords) – Bruce Adams May 10 '22 at 13:44

3 Answers3

2

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.

Felix Lehmann
  • 263
  • 2
  • 4
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.

michal915
  • 126
  • 3
0

This is very out-dated now as C++11 is widely available but as an early adopter of C++11 I used #defines for override and final to backport my code to C++03 and earlier.

I doubt this is required on any modern platforms now but you never know.

I still find it aesthetically painful that the override and virtual keywords are not both on the same side.

This question and answer are a better reference than the current one.

Bruce Adams
  • 4,953
  • 4
  • 48
  • 111