override specifier (since C++11)
Specifies that a virtual function overrides another virtual function.
Syntax
The identifier override
, if used, appears immediately after the declarator in the syntax of a member function declaration or a member function definition inside a class definition.
declarator virt-specifier-seq(optional) pure-specifier(optional) | (1) | ||||||||
declarator virt-specifier-seq(optional) function-body | (2) | ||||||||
override
may appear in virt-specifier-seq immediately after the declarator, and before the pure-specifier, if used.override
may appear in virt-specifier-seq immediately after the declarator and just before function-body.In both cases, virt-specifier-seq, if used, is either override
or final
, or final override
or override final
.
Explanation
In a member function declaration or definition, override
specifier ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.
override is an identifier with a special meaning when used after member function declarators: it's not a reserved keyword otherwise.
Example
struct A { virtual void foo(); void bar(); }; struct B : A { void foo() const override; // Error: B::foo does not override A::foo // (signature mismatch) void foo() override; // OK: B::foo overrides A::foo void bar() override; // Error: A::bar is not virtual }; int main() {}
Possible output:
main.cpp:9:10: error: 'void B::foo() const' marked 'override', but does not override 9 | void foo() const override; // Error: B::foo does not override A::foo | ^~~ main.cpp:12:10: error: 'void B::bar()' marked 'override', but does not override 12 | void bar() override; // Error: A::bar is not virtual | ^~~
See also
final specifier(C++11)
|
declares that a method cannot be overridden |