Override
keyword
C++11 override modifier informs the compiler that the new function should match a virtual method it saw in an ancestor class
- It’s a safety feature, so you don’t accidentally introduce a new method if you mistype the signature of the method you want to override
For instance,
In derived2
the compiler will issue an error for “changing the type”. Without override
, at most the compiler would give a warning for “you are hiding virtual method by same name”.
What is the purpose of the override keyword? To make sure that we are indeed overriding.
It has no effect on the executable that is created. However, can be helpful for catching bugs.
Specifying override will have have the compiler warn you if the signature does not match a superclass’ virtual method.
Where to declare override
keyword??
You need to put it in the .h
file. If you put it in the .cc
file, it complains with this error:
However, I am confused because shouldn’t it say outside a class declaration instead of class definition? Declaration vs. Definition
I think for the compiler, they use those two words interchangeably.
https://stackoverflow.com/questions/52627553/override-not-allowed-outside-a-class-definition