How to enforce the 'override' keyword?

There are few ways to do this in VC++ and equivalent ways with GCC as well.

VC++

Below are the relevant warning numbers in VC++ using Code Quality CppCoreCheck:

[C26435][2] : “Function should specify exactly one of ‘virtual’, ‘override’, or ‘final’.”
[C26433][1] : “Function should be marked with override”

To enable these two warnings:

  1. Open the Property Pages dialog for your project.

  2. Select the Configuration Properties > Code Analysis property page.

  3. Set the Enable Code Analysis on Build and Enable Microsoft Code Analysis properties.

  4. Select the Configuration Properties > Code Analysis > Microsoft property page.

  5. Setup the active rules (e.g.: C++ Core Check Class Rules contains these 2 checkers)

GCC

GCC 5.1+ has added new warning suggest-override that you can pass as command line option -Wsuggest-override.

Clang

Clang 3.5+ has -Winconsistent-missing-override, however this only detects cases if some overriding memebers or base classes use override but other overriding members do not. You might want to take a look at clang-tidy tool as well.


C++11 almost had what you want.

Originally the override keyword was part of a larger proposal (N2928) which also included the ability to enforce its usage:

class A
{
  virtual void f();
};

class B [[base_check]] : public A
{
    void f();  // error!
};

class C [[base_check]] : public A
{
  void f [[override]] ();  // OK
};

The base_check attribute would make it an error to override a virtual function without using the override keyword.

There was also a hiding attribute which says a function hides functions in the base class. If base_check is used and a function hides one from the base class without using hiding it's an error.

But most of the proposal was dropped and only the final and override features were kept, as "identifiers with special meaning" rather than attributes.