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 is related to
c++
c++11
overriding
And as an addendum to all answers, FYI: override
is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.
#include <iostream>
struct base
{
virtual void foo() = 0;
};
struct derived : base
{
virtual void foo() override
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
base* override = new derived();
override->foo();
return 0;
}
Output:
zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()
Wikipedia says:
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
In detail, when you have an object foo that has a void hello() function:
class foo {
virtual void hello(); // Code : printf("Hello!");
}
A child of foo, will also have a hello() function:
class bar : foo {
// no functions in here but yet, you can call
// bar.hello()
}
However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override
class bar : foo {
virtual void hello() override; // Code : printf("Hello Bar!");
}
override
is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:
class Foo
{
public:
virtual void func1();
}
class Bar : public Foo
{
public:
void func1() override;
}
If B::func1()
signature doesn't equal A::func1()
signature a compilation error will be generated because B::func1()
does not override A::func1()
, it will define a new method called func1()
instead.
Source: Stackoverflow.com