Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring virtual function overrides to use override keyword

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.

like image 810
Barry Avatar asked Mar 19 '15 13:03

Barry


People also ask

Is overriding compulsory if virtual keyword used?

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.

Which keyword is used to override a virtual method?

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.

Can override be done without virtual keyword?

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.

Should I use Virtual with override?

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.


1 Answers

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.

like image 63
Barry Avatar answered Sep 23 '22 02:09

Barry