Site icon Learn C++

Learn How To Use The Override Specifier In Modern C++

Learn How To Use The Override Specifier In Modern C++

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:

The override specifier generally has two purposes,

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.

[crayon-6763ecc9698ce459162055/]

and here is an example:

[crayon-6763ecc9698d8644445096/]

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,

[crayon-6763ecc9698da151435139/]

Here is a simple struct example about override and final specifiers that you can override a method of it.

[crayon-6763ecc9698dd549202561/]

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.

Exit mobile version