开发者

Why static method overrides base class non-static method?

struct B {
  void foo () {}
};

struct D : B {
  using B::foo;
  static void foo () {}
};

int main ()
{
  D obj;
  obj.foo();  // calls D::foo() !?
}

Member method and static member 开发者_开发知识库method are entirely different for 2 reasons:

  1. static method doesn't override the virtual functions in base class
  2. Function pointer signature for both the cases are different

When a method is called by an object, shouldn't the member method have higher preference logically ? (Just that C++ allows static method to be called using object, would it be considered as an overridden method ?)


The rule that you are seeing is described in ISO/IEC 14882:2003 7.3.3 [namespace.udecl] / 12 :

When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions with the same name and parameter types in a base class (rather than conflicting).

Without this rule, the function call would be ambiguous.


The issue here is that you can't overload a static method using a non-static method with the same signature.

Now, if you try:

struct D {
  void foo () {}
  static void foo () {}
};

It will trigger an error.

I'm not really sure why in case of using B::foo it is actually silently ignored without triggering an error/warning (at least on GCC 4.5.1).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜