How do I enforce the override keyword?

Is there a way to force the use of the C ++ 11 override in Visual C ++ 2012?

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

+50
c ++ override overriding c ++ 11 visual-c ++ visual-studio-2012
Nov 04
source share
2 answers

C ++ 11 almost had what you want.

The override keyword was originally part of a larger sentence ( N2928 ), which also included the ability to enforce its use:

 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 will make an error to override a virtual function without using the override keyword.

There was also a hiding attribute that says a function hides functions in a base class. If base_check used, and the function hides one of the base class without using hiding , this is an error.

But most of the sentence was dropped, and only the final and override functions were saved as "identifiers with a special value", not attributes.

+22
Nov 04
source share

There are several ways to do this in VC ++ and similar ways with GCC.

Vc ++

The following are the alert numbers in VC ++:

 C4263 (level 4) 'function': member function does not override any base class virtual member function C4266 (level 4) 'function': no override available for virtual member function from base 'type'; function is hidden 

To enable these two warnings, you can use one of the following options:

  1. Set the warning level to 4 in the project settings, and then turn off the warnings that you do not want. This is my preferred method. To disable unwanted level 4 alerts, go to project settings> C / C ++> Advanced and enter the alert numbers in the "Disable specific alerts" box.
  2. Include the two warnings above using the code.

     #pragma warning(default:4263) #pragma warning(default:4266) 
  3. Turn on the two warnings in the project settings> C / C ++> Command Prompt, and then type / w34263 / w34266. Here, the / wNxxxx option means enabling xxxx warnings at level N (N = 3 - the default level). You can also do / wdNxxxx, which disables the xxxx warning at level N.

NKU

GCC 5. 1+ added a new suggest-override warning, which you can pass as the -Wsuggest-override command-line -Wsuggest-override .

clank

Clang -Winconsistent-missing-override has a -Winconsistent-missing-override , however this only detects cases where some overriding members or base classes use override but other overriding members do not. You might also want to take a look at the clang-tidy tool.

+7
Dec 12 '16 at 21:05
source share



All Articles