开发者

override on non-virtual functions

开发者 https://www.devze.com 2023-04-07 05:13 出处:网络
The C++11 FDIS it says If a virtual function is marked with the virt-specifier override and does not override a member function of

The C++11 FDIS it says

If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed. [ Example:

struct B {
    virtual void f(int);
};
struct D : B {
    void f(long) override; // error: wrong signature overriding B::f
    void f(int) override; // OK
};

What if B::f would not have been marked virtual? Is the program ill-formed, then? Or is override then to be ignored`. I can not find any handling of this case in the std text.

Update 1/2 (merged) I forwarded a request to the C++ Editors to look into things. Thanks Johannes to pointing that out to me.

  • "void f(long) override" do开发者_如何转开发es not override a function, esp. no virtual one,
  • therefore it is not virtual
  • therefore the text "If a virtual function is marked with..." does not apply
  • therefore the example does not match the text.

But by realizing this I found, that the intention of the "override" contextual keyword can not be met: if a typo in the function name or the wrong argument type does make the function itself non-virtual, then the standard's text never applies -- and "override" is rendered useless.

The best possible solution may be

  • putting "virtual" in front of the example's functions


What if B::f would not have been marked virtual? Is the program ill-formed, then?

Yes, it is. Because in order to override something, that something has to be virtual. Otherwise it's not overriding, it's hiding. So, the positive answer follows from the quote in your question.


If B:f was non-virtual, then both D:f functions would be ill-formed.


Yes, the program is ill formed when override is added to any non-virtual function.

Generally, functions with differing signatures (overloaded), are as different as functions with different names. The example given in the Spec is not meant to imply that the function name effects override. It's meant to show the common error that override is designed to prevent.

0

精彩评论

暂无评论...
验证码 换一张
取 消