Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Why member function has priority over global function

Why in the next program the member function foo has priority over the global foo although the global one match the type?

#include <iostream>
using namespace std;

void foo(double val) { cout << "double\n";}

class obj {
public:
  void callFoo() { foo(6.4); }
private:
  void foo(int val) {cout << "class member foo\n"; }
};

int main() { 
  obj o;
  o.callFoo();
}
like image 687
user890739 Avatar asked Sep 16 '14 07:09

user890739


1 Answers

Because the member function named foo could be found at the class scope, and then name lookup will stop, so the global version foo won't be considered for overload resolution, even if the global version is more appropriate here. It is a kind of name hiding.

If you want to call the global version, you could explicitly call it by ::foo(6.4);.

And here is a workaround to bring the global function into overload resolution.

Reference for Unqualified name lookup

like image 124
songyuanyao Avatar answered Sep 22 '22 19:09

songyuanyao