Missing 'virtual' qualifier in function declarations

旧巷老猫 提交于 2019-12-23 14:58:10

问题


Whilst trawling through some old code I came across something similar to the following:

class Base
{
public:
    virtual int Func();
    ...
};

class Derived : public Base
{
public:
    int Func(); // Missing 'virtual' qualifier
    ...
};

The code compiles fine (MS VS2008) with no warnings (level 4) and it works as expected - Func is virtual even though the virtual qualifier is missing in the derived class. Now, other than causing some confusion, are there any dangers with this code or should I change it all, adding the virtual qualifier?


回答1:


The virtual will be carried down to all overriding functions in derived classes. The only real benefit to adding the keyword is to signify your intent a casual observer of the Derived class definition will immediately know that Func is virtual.

Even classes that extend Derived will have virtual Func methods.

Reference: Virtual Functions on MSDN. Scroll down the page to see

The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual.




回答2:


Here's an interesting consequence of not needing to declare overriding functions virtual:

template <typename Base>
struct Derived : Base
{
    void f();
};

Whether Derived's f will be virtual depends on whether Derived is instantiated with a Base with a virtual function f of the right signature.




回答3:


Someone told me once that very old C++ compilers, not conforming to the spec, require virtual to be set for all subclasses. That's not an issue anymore.




回答4:


One danger of following this practice is that people may not realise they need the virtual keyword on functions which are intended to be virtual. This is most likely to be people coming from languages where there is no concept of non-virtual functions (eg: Java, REALbasic). As a corollary, you can't tell when virtual has been deliberately omitted because a function is supposed to be non-virtual.

I suspect some code analysis tools may also not be smart enough to pick up the inherited virtuality.



来源:https://stackoverflow.com/questions/340437/missing-virtual-qualifier-in-function-declarations

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