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
.
To override a method, the override keyword is mandatory not virtual . The difference is that you hide the method if you omit the virtual keyword, and not override it.
The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into a derived class. The new keyword is used to hide a method, property, indexer, or event of base class into derived class.
You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
So the general advice is, Use virtual for the base class function declaration. This is technically necessary. Use override (only) for a derived class' override.
Looks like the GCC 5.1 release added exactly the warning I was looking for:
-Wsuggest-override
Warn about overriding virtual functions that are not marked with the override keyword.
Compiling with -Wsuggest-override
-Werror=suggest-override
would then enforce that all overrides use override
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With