How to enforce the 'override' keyword?

user541686 picture user541686 · Nov 4, 2012 · Viewed 7.9k times · Source

Is there any way to enforce the usage of the C++11 override keyword in Visual C++ 2012?

(i.e. if I forget to say override, then I want to get a warning/error.)

Answer

Jonathan Wakely picture Jonathan Wakely · Nov 4, 2012

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.