Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is override optional in C++?

I understand the purpose of the C++ override, however am a bit confused by it's implementation compared to other higher level languages, where its use is required by default.

The C++11 wiki page describes it as a "technically identifier for declarator attribute" but does not elaborate as to why it is not simply a keyword for the language.

like image 347
nonathaj Avatar asked Mar 24 '16 21:03

nonathaj


People also ask

Is @override optional?

In any case, the use of @override is optional.

Is the override keyword required?

You don't need the override identifier to do this in C++, it simply enforces that you are doing it properly.

Is the @override annotation optional?

It was made optional because they didn't want it as part of the language. Dart doesn't require you to write anything to override a method. So really, it's not optional, it's not there at all from the language perspective.

What is the purpose of override keyword?

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.


2 Answers

It is optional to maintain backwards compatibility with C++03. Making it non-optional would have broken all the code*.

Similarly, making override a keyword would have broken any code that used the name override.


OK, not literally all the code, but a lot of it.

like image 126
juanchopanza Avatar answered Sep 18 '22 23:09

juanchopanza


Technically, C++11 does not behave much differently from Java here (which is a typical example for one of the "other higher level languages" which you mention). A wrong override will be a compilation error, just like a wrong @Override in Java. A missing override will not be a compilation error, just like a missing @Override will not be a compilation error in Java.

The only real difference I can see is that Java tools have traditionally had better support to detect a missing @Override, and that Java users are traditionally encouraged to treat the corresponding warning as an error, whereas C++ compilers have been quite slow so far at adding warning options for missing overrides.

But we're getting there; Clang now has -Winconsistent-missing-override, and newer GCCs have -Wsuggest-override. All you have to do is enable those warnings and treat them as errors, either forcibly by the compiler or simply by convention.

As for why it's not simply a keyword: backward compatibility with older code.

like image 45
Christian Hackl Avatar answered Sep 17 '22 23:09

Christian Hackl