Is there any point in using `override` when overriding a pure virtual function?

R2B2 picture R2B2 · Sep 27, 2017 · Viewed 9.5k times · Source

For example:

class Base {
  virtual void my_function() = 0;
};

class Derived : Base {
  void my_function() override;
};

From what I read, the override keyword is used to make sure that we have the correct signature in the function that we are overriding, and it seems to be its only use.

However, in the case of a pure virtual function, the compiler would throw an error if we used an incorrect signature in the Derived class (or Base class, depending on how one see things). So, is there any point in adding override at the end of Derived::my_function() declaration?

Answer

Vittorio Romeo picture Vittorio Romeo · Sep 27, 2017

However, in the case of a pure virtual function, the compiler would throw an error if we used an incorrect signature in the Derived class

No, this compiles:

class Base {
  virtual void my_function() = 0;
};

class Derived : Base {
  void my_function(int);
//                 ^^^ mistake!
};

While this does not:

class Base {
  virtual void my_function() = 0;
};

class Derived : Base {
  void my_function(int) override;
};

error: void Derived::my_function(int) marked override, but does not override


The error you're talking about only occurs when instantiating Derived - override allows you to catch the mistake earlier and makes the definition of Derived clearer/more readable.