Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit override of virtual function

I just discovered that C++/CLI has a keyword that is not present (AFAIK) on standard C++: override.

I don't know much about C++/CLI, so, can someone explain for which purpose is it included there, and if is it a desirable feature to be added to C++?

like image 425
kunigami Avatar asked Jan 28 '11 19:01

kunigami


2 Answers

override is a special keyword extension from Microsoft that can be used in C++/CLI and Visual C++ implementations. It is similar to the @Override annotation in Java or override in C#, and provides better compile time checks just in case you didn't override something you meant to.

From the first link:

override indicates that a member of a managed type must override a base class or a base interface member. If there is no member to override, the compiler will generate an error.

override is also valid when compiling for native targets (without /clr). See Override Specifiers and Native Compilations for more information.

override is a context-sensitive keyword. See Context-Sensitive Keywords for more information.

As of the C++11 standard, the override specifier is now a standardized keyword. Support is still limited, and as per this page from Apache StdCxx, override is supported by GCC 4.7+, Intel C++ 12.0+, and Visual C++ 2012 (with pre-standardization support in Visual C++ 2005).

like image 140
逆さま Avatar answered Sep 19 '22 10:09

逆さま


It helps the compiler catch your mistakes two ways:

  1. If you declare a function with override in your class, but the base class doesn't have that function, then the compiler can tell you that you're not overriding what you thought you were. If override weren't available, then the compiler wouldn't be able to recognize your error — it would simply assume that you intended to introduce a new function.

  2. If you have a function in your descendant class (without override), and then you declare that same function as virtual in the base class, the compiler can tell you that your change in the base class has affected the meaning of the original declaration in the descendant. The descendant will either need to use override, or you'll need to change the signature of one of the functions.

This feature is being added to C++0x already.

like image 34
Rob Kennedy Avatar answered Sep 18 '22 10:09

Rob Kennedy