Reputation: 311315
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
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 classBase
and in a classDerived
, derived directly or indirectly fromBase
, a member functionvf
with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (or absence of same) asBase::vf
is declared, thenDerived::vf
is also virtual (whether or not it is so declared) and it overridesBase::vf
. For convenience we say that any virtual function overrides itself.
Upvotes: 11
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