What is the 'override' keyword in C++ used for? [duplicate]
The override
keyword serves two purposes:
- It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."
- The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.
To explain the latter:
class base
{
public:
virtual int foo(float x) = 0;
};
class derived: public base
{
public:
int foo(float x) override { ... } // OK
}
class derived2: public base
{
public:
int foo(int x) override { ... } // ERROR
};
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".
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()
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.