The specifier override
has a special meaning in C++11 onwards, if appended at the end of function signature. This signifies that a function is
virtual
There is no run time
significance of this specifier as is mainly meant as an indication for compilers
The example below will demonstrate the change in behaviour with our without using override.
Without override
:
#include <iostream>
struct X {
virtual void f() { std::cout << "X::f()\n"; }
};
struct Y : X {
// Y::f() will not override X::f() because it has a different signature,
// but the compiler will accept the code (and silently ignore Y::f()).
virtual void f(int a) { std::cout << a << "\n"; }
};
With override
:
#include <iostream>
struct X {
virtual void f() { std::cout << "X::f()\n"; }
};
struct Y : X {
// The compiler will alert you to the fact that Y::f() does not
// actually override anything.
virtual void f(int a) override { std::cout << a << "\n"; }
};
Note that override
is not a keyword, but a special identifier which only may appear in function signatures. In all other contexts override
still may be used as an identifier:
void foo() {
int override = 1; // OK.
int virtual = 2; // Compilation error: keywords can't be used as identifiers.
}