Modern C++ has many additions compared to the original C++ standard. Regarding virtual overrides, C++11 tends to tighten the rules, to detect some problems that often arise. To achieve this goal C++11 introduces two new contextual keywords, the final and the override specifiers. The override specifier is used to redefine the base class function in a derived class with the same signature i.e. return type and parameters. This override specifier is used with a C++ compiler that is compatible with C++11 and the other higher C++ standards. In this post, we explain an override specifier in modern C++.
What Is the override specifier in C++?
The override specifier (keyword) is used to redefine the base class function in a derived class with the same signature i.e. return type and parameters. In other words, it specifies that a method overrides a virtual method declared in one of its parent classes. Regarding virtual overrides, C++11 tends to tighten the rules, to detect some problems that often arise.
To achieve this goal C++11 introduces two new contextual keywords:
- final specifies that a method cannot be overridden, or a class cannot be derived.
- override specifies that a method overrides a virtual method declared in one of its parent classes.
The override specifier generally has two purposes,
- It shows that a given virtual method is overriding a virtual method of the base class.
- It indicates to the compiler that you are not adding or altering new methods that you think are overrides, and the compiler knows that is an override.
In this post, we explain how to use the override specifier in C++.
How to use the override specifier in C++?
The override specifier is used to designate member functions that override a virtual function in a base class.
and here is an example:
Is there a simple example of how to use the override specifier in C++?
Here is a simple class example about override and final specifiers that you can override a method of it,
Here is a simple struct example about override and final specifiers that you can override a method of it.
In both examples above, we commented lines that will cause errors, you can check errors by removing the //
at the start of the comments.
For more information on this feature, see Explicit virtual overrides Proposal document.
C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise version.