开发者

in c++ when subclassing why sometimes need to add virtual keyword to overridden function?

Why do I sometimes see in C++ examples when talking about subclassing / inheritance, the base class has virtual keyword and sometimes the over开发者_如何转开发ridden function has also the virtual keyword, why it's necessary to add to the subclass the virtual key word sometimes? For example:

class Base 
{
  Base(){};
  virtual void f()
     ......
  }
};

class Sub : public Base
{
  Sub(){};
  virtual void f()
     ...new impl of f() ...
  }
};


It is not necessary, but it helps readability if you only see the derived class definition.

§10.3 [class.virtual]/3

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 and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides 97) Base::vf.

Where footnote 97) basically states that if the argument list differs, the function will not override nor be necessarily virtual

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜