Summary: In this tutorial, we will learn about the override keyword in C++ with examples.

override keyword in C++ is used in the postfix of the derive class’s function declaration to ensures that it uses the same function signature to override a base class virtual method.

Basically, override keyword forces the compiler to check that the particular function is actually overriding a base class method rather than adding a new method to the program.

Let’s see an example to have a clear ides about the significance of override keyword.


Consider the following C++ program.


without override

In the Wallpaper (Derived) class, we tried to override the color function of the Picture (Base) class but we failed to do so because we forgot that the 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 the 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’s 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.

In this tutorial, we have learned the significance of the override keyword in C++ with examples.

Leave a Reply