This question already has an answer here:
I am a beginner in C++. I have come across override
keyword used in the header file that I am working on. May I know, what is real use of override
, perhaps with an example would be easy to understand.
This question already has an answer here:
I am a beginner in C++. I have come across override
keyword used in the header file that I am working on. May I know, what is real use of override
, perhaps with an example would be easy to understand.
Wikipedia says:
In detail, when you have an object foo that has a void hello() function:
A child of foo, will also have a hello() function:
However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override
And as addendum to all answers, FYI:
override
is not a keyword, but a special kind of identifier! It has meaning only in context of declaring/defining virtual functions, in other contexts it's just an ordinal identifier. For details read 2.11.2 of The Standard.Output:
The
override
keyword serves two purposes:To explain the latter:
In
derived2
the compiler will issue an error for "changing the type". Withoutoverride
, at most the compiler would give a warning for "you are hiding virtual method by same name".override
is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:If
B::func1()
signature doesn't equalA::func1()
signature a compilation error will be generated becauseB::func1()
does not overrideA::func1()
, it will define a new method calledfunc1()
instead.