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

Introduction to Override Keyword

The override keyword in C++ is used in the postfix of the function declaration of the derived class to ensure that it uses the same function signature to override the base class virtual method.

In simple terms, the override keyword forces the compiler to check that the particular method is actually overriding the base class method instead of adding a new method to the program.

Recommended:

Consider the following program for example:

#include <iostream>
using namespace std;
 
class Picture{
public:
  void color(string rgb){
    cout << "This picture is Coloured with " << rgb << endl;
  }
};
 
class Wallpaper: public Picture{
public:
  void color(){
    cout<< "Wallpaper is Coloured \n";
  }
};
 
int main() 
{
  Wallpaper wall;
  wall.color();
 
  return 0;
}

Output:

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 this type of mistake we use the keyword override in the declaration of the overriding function.

Postfix the overriding function declaration with the override keyword and compile it again:

class Wallpaper: public Picture{
public:
  void color() override{
    cout<< "Wallpaper is Coloured \n";
  }
};

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 receive a message from the compiler stating that we are trying to override the color() function but missing a parameter.

So let’s retype the color function of the wallpaper class to successfully override the color function of the picture class:

Example using Override Keyword in C++

#include <iostream>
using namespace std;
 
class Picture{
public:
  virtual void color(string rgb){
    cout << "This picture is Coloured with " << rgb << endl;
  }
};
 
 
class Wallpaper: public Picture{
public:
  void color(string rgb) override{
    cout<< "Wallpaper is Coloured with "<< rgb << endl;
  }
};
 
int main() 
{
 
  Wallpaper wall;
  wall.color("Red");
 
  return 0;
}

Output:

with override

This way we can avoid creating a new function by following the compiler message.

Overview of Override Keyword

The 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 the same name then it should be declared virtual i.e. it is intended to be overridden.
  • If the function in the base class is virtual, the derived class function with the same name should also have the same signature.

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

Leave a Reply