override is a specifier which let compiler check if the virtual function is meant to be override in the derive class. If the virtual function is meant to be override but is not getting overridden because of different signature or return type, compiler would raise compilation error if override specifier is used.
For example:
#include <iostream>
class Base
{
public:
virtual void msg(int a)
{
std::cout << "From base " << a << '\n';
}
};
class Derived : public Base
{
public:
void msg(int a) const
{
std::cout << "From derived " << a << '\n';
}
};
int main(int argc, char const *argv[])
{
Derived d;
d.msg(1);
Base &ref{d};
ref.msg(2);
return 0;
}We might expect msg from the derived class to be called for ref.msg(2) but it calls the base class version because msg of derived class has const in the signature. To let compiler enforce such overrides during the compilation time, we can use override specifier after const as shown below:
class Derived : public Base
{
public:
void msg(int a) const override
{
std::cout << "From derived " << a << '\n';
}
};Now, when compiled, compiler would raise error saying msg is marked as override but it would not be getting overridden. This helps us finding the issues in early phase rather than debugging when the program runs.