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

倾然丶 夕夏残阳落幕 提交于 2019-12-07 01:54:19

问题


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?


回答1:


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.




回答2:


They are identical.

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



来源:https://stackoverflow.com/questions/17317083/can-a-virtual-function-be-overridden-by-a-non-virtual-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!