What is the purpose of the override and final keywords?
Last updated
Both are C++11 contextual keywords that make virtual-function intent explicit and let the compiler catch mistakes: override asserts that a function really overrides a base virtual, and final forbids further overriding (on a function) or further derivation (on a class).
override:Compile error if the function does not match a base virtual (wrong name, signature, or constness), catching silent bugs where you accidentally create a new function instead of overriding.
Documents intent and improves readability.
final:On a virtual function: prevents any derived class from overriding it further.
On a class: prevents inheriting from that class at all.
Can enable devirtualization optimizations, since the compiler knows the call target is fixed.
Note: They are not reserved words: they only have meaning in these specific positions, so existing identifiers named
overridestill work.
[lang:cpp]
struct Base { virtual void f(); };
struct Derived : Base {
void f() override; // verified against Base::f
void g() final; // (if g were virtual) no further override
};
struct Last final : Derived {}; // Last cannot be a base class
- https://www.tutorialspoint.com/cplusplus/cpp_override_specifier.htm
- https://tcs.rwth-aachen.de/docs/cpp/reference/en.cppreference.com/w/cpp/language/override.html
- https://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/cpp/override-specifier.md
- https://www.fluentcpp.com/2020/02/21/virtual-final-and-override-in-cpp/
- https://www.modernescpp.com/index.php/override-and-final/
- https://dmoj.uclv.edu.cu/docs/cpp/en/w/cpp/keyword/final.html
- https://www.vervecopilot.com/interview-questions/how-can-understanding-final-in-c-elevate-your-interview-and-professional-presence
- https://arne-mertz.de/2015/12/modern-c-features-override-and-final/