Override keyword in C++ forces the derived class to use the same function signature as present in the base class if the same function name has been used.

Let’s understand the significance of C++ override keyword with an Example.


Consider the following C++ program.


without override

In the Wallpaper (Derived) class, we tried to override the color function of Picture (Base) class but we failed to do so because we forgot that color function accepts an argument.

To prevent these types of mistake we use override keyword in the function declaration of overriding function.

Postfix the overriding function declaration with override keyword and recompile it.

The compiler gives the following error.

main.cpp:7:16: note: hidden overloaded virtual function'Picture::color' declared here: different number of parameters (1 vs 0)
virtual void color(string rgb){

We explicitly get a message from the compiler stating that we are trying to override the color() function but missing a parameter.

So let’s rewrite the color() function in Wallpaper class with override specifier to override the Picture class color() function.

with override

Thus, override keyword serves the following purpose in C++:

  • Check if there is a function with the same name in the base class
  • If there is a function with same name then it should be declared virtual i.e it is intended to be overriden.
  • If the function in base class is virtual, then the function signature should also be same.

If you have any doubts then comment below.

Leave a Reply