Eric
Eric

Reputation: 97631

Can a virtual function be overridden by a non-virtual function?

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?

Upvotes: 6

Views: 328

Answers (2)

hmjd
hmjd

Reputation: 122001

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.

Upvotes: 16

Karthik T
Karthik T

Reputation: 31952

They are identical.

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

Upvotes: 4

Related Questions