C++11 added override
to ensure that member functions you write that you intend to override base-class virtual functions actually do (or won't compile).
But in a large object hierarchy, sometimes you could accidentally end up writing a member function that overrides a base-class virtual when you didn't intend it! For instance:
struct A {
virtual void foo() { } // because obviously every class has foo().
};
struct B : A { ... };
class C : B {
private:
void foo() {
// was intended to be a private function local to C
// not intended to override A::foo(), but now does
}
};
Is there some compiler flag/extension that would at least issue a warning on C::foo
? For readability and correctness, I just would like to enforce that all overrides use override
.
GCC and Clang are covered by other answers. Here's same for VC++ from my other answer:
Below are the relevant warning numbers in VC++:
To enable these two warnings, you can use one of following options:
Enable above two warnings using code.
Enable above two warnings in project settings > C/C++ > Command Line and then enter /w34263 /w34266. Here /wNxxxx option means enable xxxx warnings in Level N (N = 3 is default level). You can also do /wdNxxxx which disables the xxxx warning in level N.
Looks like the GCC 5.1 release added exactly the warning I was looking for:
Compiling with
-Wsuggest-override
-Werror=suggest-override
would then enforce that all overrides useoverride
.There are two things you can do.
First, Clang 3.5 and higher have a
-Winconsistent-missing-override
warning (triggered by-Wall
). This does not quite work for your example, but only if you would add avoid foo() override {}
toclass B
and not inclass C
. What you actually want is-Wmissing-override
, to locate all missingoverride
, not just the inconsistently missing ones. That is currently not provided, but you might complain on the Clang mailinglist and they might add it.Second, you use Howard Hinnant's trick to temporarily add
final
to the base class member function and recompile. The compiler will then locate all further derived classes that attempt to override thevirtual
base member function. You can then fix the missing ones. It's a bit more work and requires frequent rechecking when your class hierarchy expands.The problem I see with
-Werror=suggest-override
is that it does not allow you to write the following:Even though there is an implicit
override
here. The-Werror=suggest-override
does not ignore this (like it should, since theoverride
is redundant in this case)But it is more complicated than that... If you write
It means a completely different thing than
The first case does not need to override anything! The second does.
So I am assuming the GCC check is implemented this way (i.e. to sometimes accept the redundant
override
) in order to get the last case right. But this does not play well e.g. with clang-tidy, which will correctly remove the override when final is sufficient (but then GCC compilation will fail...)