Are there any subtleties in using both the virtual and override keywords in C++11?

The virtual keyword has no effect when you are overriding. A derived function that is a signature match for a virtual function defined in a base class will override the base definition, and the override will be entered in the vtable, whether the virtual keyword is used in the derived class or not.

Because the override keyword will cause a compile error if overriding is not happening, the virtual keyword is useless in combination.

Here, have a cheatsheet:

| Keyword used | Matching virtual function in base class | Result                   |
|--------------|-----------------------------------------|--------------------------|
| Neither      | No                                      | New non-virtual function |
| Neither      | Yes                                     | Override                 |
| virtual      | No                                      | New virtual function     |
| virtual      | Yes                                     | Override                 |
| override     | No                                      | Compile error            |
| override     | Yes                                     | Override                 |
| Both         | No                                      | Compile error            |
| Both         | Yes                                     | Override                 |

Late to the game, but this C++ Core Guideline seems relevant here:

C.128: Virtual functions should specify exactly one of virtual, override, or final

Reason

Readability. Detection of mistakes. Writing explicit virtual, override, or final is self-documenting and enables the compiler to catch mismatch of types and/or names between base and derived classes. However, writing more than one of these three is both redundant and a potential source of errors.

It's simple and clear:

  • virtual means exactly and only "this is a new virtual function."
  • override means exactly and only "this is a non-final overrider."
  • final means exactly and only "this is a final overrider."

Tags:

C++

C++11