正常
override specifier (C++11)
In a Nutshell
Adding override at the end of a virtual function declaration asks the compiler to verify that you really did override a base-class virtual function; a signature mismatch or a non-virtual base-class function becomes an immediate compile error.
Header
None (a language-keyword-level feature)
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Function declaration | return_type func_name(params) override; | Used at declaration time to ensure you are overriding a base-class virtual function |
| Function definition (in-class) | return_type func_name(params) override { ... } | Used when defining the function inside the class |
| Pure virtual override | return_type func_name(params) override = 0; | override appears before = 0 |
| Combined with final | return_type func_name(params) override final; | Can be combined with final in either order |
| Destructor override | ~Derived() override; | Can be used to check overrides of virtual destructors |
Minimal Example
C++
// Standard: C++11
#include <iostream>
struct Base { virtual void foo() { std::cout << "Base\n"; } };
struct Derived : Base {
// void foo(int) override; // compile error: signature mismatch
void foo() override { std::cout << "Derived\n"; }
};
int main() {
Derived d;
d.foo();
}Embedded Applicability: High
- Zero runtime overhead; it is purely a compile-time static check
- Embedded code often has hardware abstraction layers (HALs) built on multi-level inheritance, and
overrideeffectively prevents the silent errors caused by modifications to a base-class interface - No impact on code size or execution speed, a good fit for resource-sensitive contexts
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 4.7 | 3.0 | 2012 |
See Also
Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0