VOOZH about

URL: https://www.geeksforgeeks.org/cpp/override-keyword-c/

⇱ override identifier in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

override identifier in C++

Last Updated : 27 Nov, 2024

Function overriding is a redefinition of the base class function in its derived class with the same signature i.e. return type and parameters. 
But there may be situations when a programmer makes a mistake while overriding that function. So, to keep track of such an error, C++11 has come up with the override identifier.

If the compiler comes across this identifier, it understands that this is an overridden version of the function of the base class. It will make the compiler check the base class to see if there is a virtual function with this exact signature. And if there is not, the compiler will show an error.

Let's understand through the following example: 


Output
Compiled successfully

Explanation: Here, the user intended to override the function func() in the derived class but did a silly mistake and redefined the function with a different signature. Which was not detected by the compiler. However, the program is not actually what the user wanted. So, to get rid of such silly mistakes to be on the safe side, the override identifier can be used. 

Below is a C++ example to show the use of override identifier in C++.


Output(Error)

main.cpp:23:10: error: ‘void derived::func(int)’ marked ‘override’, but does not override
23 | void func(int a) override
| ^~~~

In short, it serves the following functions. It helps to check if: 

  • There is a method with the same name in the parent class.
  • The method in the parent class is declared as "virtual" which means it was intended to be rewritten.
  • The method in the parent class has the same signature as the method in the subclass.
Comment