Drew Noakes
Drew Noakes

Reputation: 311315

Purpose of making overridden virtual function non-virtual

Consider the following classes in C++11:

class Base
{
public:
  virtual void foo() = 0;
}

class Sub1 : public Base
{
public:
  virtual void foo() override {};
}

class Sub2 : public Base
{
public:
  void foo() override {};
}

What are the consequences of making the overridden function non-virtual as in Sub2?

Upvotes: 2

Views: 550

Answers (2)

T.C.
T.C.

Reputation: 137404

An override of a virtual function is always virtual regardless of whether it's declared as such. Thus, having or not having the virtual keyword in the declaration of Sub2::foo() has no effect whatsoever as far as the language is concerned, since the override keyword means that the function must override a member function of a base class. From §10.3 [class.virtual]/p2 of the standard, emphasis added:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf. For convenience we say that any virtual function overrides itself.

Upvotes: 11

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145457

Omitting the word virtual does not make the function non-virtual. It does reduce the verbosity, the amount of visual noise, or in short, the way that the source code text can make an impression of just being too long-winded without any specific part of it introducing anything really new that can capture the reader's attention so that it all appears more or less like a gray mass of text, which of course can lead to some important details being overlooked, which is to say, inadvertently ignored. The override keyword is preferable.

Upvotes: 9

Related Questions