Can a virtual function be overridden by a non-virtual function?
Asked Answered
T

2

6

In this code:

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

class Derived1 : public Base{
public:
    virtual void method() override { }
};

class Derived2 : public Base{
public:
    void method() override { }
};

Is there any difference between Derived1 and Derived2?

Tranquillize answered 26/6, 2013 at 10:2 Comment(4)
Derived2::method2 is virtual.Ba
if syntax allows it. (not checked) then derived2->method() will also be virtual (implicit though)Carlton
@R.MartinhoFernandes: So the virtual keyword is implied?Tranquillize
@Alex: Compiles fine for me under gcc-4.7.2Tranquillize
U
16

From section 10.3 Virtual functions of the c++11 standard (draft n3337) point 2:

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 refqualifier (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.

So Derived2::method is also virtual, even though it is not explicitly declared as such.

Unceremonious answered 26/6, 2013 at 10:4 Comment(5)
Is it ever desirable to declare the member without the virtual keyword? Can GCC be made to spit out a warning when that happens?Tranquillize
@Eric: Some argue that marking the derived function virtual serves as documentation, others argue that it is unnecessary code bloat. In practice it doesn't really matter either way.Ferree
With C++11 one can use the override keyword to indicate that a function in a derived class is virtual.Lithium
@Eric, I agrree with what user1131467. Personally, I prefer it for documentation. As for compiler switches to issue warnings I am unsure.Unceremonious
Perfect answer. Probably the confusion of the op comes from the fact that in newer languages, such as Java and C#, it is possible to declare a method to stop being virtual.Mowbray
L
4

They are identical.

virtual is optional when actually overriding a function. It is mandatory only when marking a function in the base class.

Labors answered 26/6, 2013 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.