Should I use virtual, override, or both keywords?

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. For instance, 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 virtual in the 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.

Example:

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


Notes:
¹ 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)