override


Keyword: override

The override keyword in C++ is used in object-oriented programming to indicate that a member function in a derived class is intended to override a virtual function in a base class. This keyword is part of modern C++ (introduced in C++11) and serves as a way to improve code clarity, maintainability, and safety.

What Does override Do?

When you use the override keyword, the compiler checks that the function is indeed overriding a virtual function from the base class. If it is not, the compiler will generate an error. This helps prevent subtle bugs that can occur if you accidentally misspell a function name or mismatch the function signature.

Example without override

In this case, Display() in the Derived class is not overriding display() in the Base class due to the case difference in the function name. However, this will not produce any compiler errors, and the Base::display() function will be called instead of the intended Derived::Display(), leading to unexpected behavior.

Example With override (Safety Check)

In this example, if there were a mistake such as a misspelled function name or an incorrect signature, the compiler would catch the error because of the override keyword.

Benefits of Using override:

Common Usage Scenarios:

Summary

Previous Page | Course Schedule | Course Content