override specifier

From cppreference.com
< cpp‎ | language
 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
virtual function
override specifier (C++11)
final specifier (C++11)
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Specifies that a virtual function overrides another virtual function.

Contents

[edit] Syntax

The identifier override, if used, appears immediately after the declarator in the syntax of a member function declaration or a member function definition.

declarator virt-specifier-seq(optional) pure-specifier(optional) (1)
declarator virt-specifier-seq(optional) function-body (2)
1) In a member function declaration, override may appear in virt-specifier-seq immediately after the declarator, and before the pure-specifier, if used.
2) In a member function definition, override may appear in virt-specifier-seq immediately after the declarator and just before function-body (which may begin with a member initializer list)

In both cases, virt-specifier-seq, if used, is either override or final, or final override or override final.

[edit] Explanation

In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from the 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.

[edit] 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: B::bar is not virtual
};

[edit] See also