Is there any point in using `override` when overriding a pure virtual function?
Solution 1:
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)
markedoverride
, 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.
Solution 2:
Yes, it is a good idea to use override
keyword consistently as a defensive practice.
Consider a redesign when the author of the Base
decides that my_function
should no longer be a pure virtual, and also that it should take a new parameter. With override
in place the compiler will catch this problem; without an override
your Derived
class would continue to compile.