Daniel Daniel - 15 days ago 5x
C++ Question

virtual? override? or both? C++

in the last weeks something is bugging my brain about virtual and override.
I've learned that when you do inheritance with virtual function you have to add 'virtual', to let the compiler know to search for the right function.
Afterwards I learned also that in c++ 11 there is a new keyword - override. Now I'm a little confused; Do i need to use both virtual and override keywords in my program, or it's better to use only one of them?

To explain myself - code examples of what i mean:

class Base
virtual void print() const = 0;
virtual void printthat() const = 0;
virtual void printit() const = 0;

class inhert : public Base
// only virtual keyword for overriding.
virtual void print() const {}

// only override keyword for overriding.
void printthat() const override {}

// using both virtual and override keywords for overriding.
virtual void printit() const override {}

What is the best method?


When you override a function you don't technically need to write either virtual or override.

The original base class declaration needs the keyword virtual to mark it as virtual.

In the derived class the function is virtual by way of having the ┬╣same type as the base class function.

However, an override can help avoid bugs by producing a compilation error when the intended override isn't technically an override. E.g. that the function type isn't exactly like the base class function. Or that a maintenance of the base class changes that function's type, e.g. adding a defaulted argument.

In the same way, a virtual keyword in the derived class can make such a bug more subtle, by ensuring that the function is still is virtual in further derived classes.

So the general advice is,

  • Use virtual for the base class function declaration.
    This is technically necessary.

  • Use override (only) for a derived class' override.
    This helps maintenance.


struct Base { virtual void foo() {} };
struct Derived: Base { void foo() override {} };

┬╣ C++ supports covariant raw pointer and raw reference results. With covariance the type of the override isn't exactly the same. It just has a compatible type.