I'm curious as to why the new C++11 keyword override
is forced to appear after a method declaration in a manner consistent with const
instead of virtual
?
class SomeBaseClass {
virtual void DoPolymorphicBehavior() = 0;
...
class SomeDerrivedClass : public SomeBaseClass {
void DoPolymorphicBehavior() override;
...
Why in the world not allow it in the same exact position (and even instead of) virtual
class SomeBaseClass {
virtual void DoPolymorphicBehavior() = 0;
...
class SomeDerrivedClass : public SomeBaseClass {
override void DoPolymorphicBehavior();
...
This would have allowed me to do search & replaces in my source files for derived classes to trivially make use of the new keyword and thus get help from the compiler at finding errors. However, because C++11 puts it in a different position syntactically, I would have to manually update literally several thousands of lines of source code in order to gain any benefit from the new compiler feature.
Surely there was a good reason behind this choice?
The declaration specifier sequence that appears before the function name can contain an identifier (for example, the return type of the function). Imagine some existing code had a return type of override
:
override foo();
Or even a variable called override
:
int override;
Introducing a new keyword override
would break any existing code that contained an identifier named override
because keywords are reserved.
So instead of introducing a new keyword, they introduced a contextual keyword: override
(and also final
). A contextual keyword is identified as a keyword by its syntactic position. It is still fine to have identifiers called override
and final
in your program. If these identifiers appear after the argument list in a function declaration, they have a special meaning.
So the reason it is placed after the function arguments is because introducing new keywords will break old code and if the compiler sees override
here they know exactly what it means, since no other identifier could appear here.
It's not a keyword and that is the answer to your question as well.
It is an identifier with a special meaning in some contexts. If it were allowed to appear at the start of the declaration it could be ambiguous with, say, a user defined return type name.
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