The override specifier was added in C++11 and is used to show that a method is overriding another method in a base class. When you use this specifier the compiler will help you to make sure that you are using the same signature in the new method as in the base class method.
// This method is virtual and can be overriden in a subclass
virtual void VirtualMethod()
// This method is not virtual and cannot be overriden in a subclass
// This method is const and when overriding it, the const must be preserved.
virtual void ConstMethod() const
class SubClass : public BaseClass
/* This is the correct usage for override,
the method has the same signature as base class */
virtual void VirtualMethod() override
// Compile Error! Cannot override if the method is not virtual !
void NonVirtualMethod() override
// The signature must match the base class method, including the const.
virtual void ConstMethod() const override
Why should we use this?
- Because this makes your code more clear, adding override to your function makes it clear to anyone reading the code later that this is an override of a base class function.
- It is very easy to accidentally create a new virtual function in a derived class when you intended to override a function in a base class by making an error in the signature of the function (like forgetting a const).