This code snippet doesn't compile:
struct M {
int i;
int j;
};
void f(M& m) {
m.i++;
}
struct N {
M m;
void f(int i) {
f(m); // compilation error
}
};
clang says:
No viable conversion from 'M' to 'int'
Seems my member function hides global function.
I changed the error line into ::f(m)
to help name resolution, but still fails. Does it mean that in c++ member function, cannot call global overload function with same name but different parameter list?
How to fix this? Thanks!
c++ member function hides global function
The problem is that for the call expression f(m)
name lookup finds the member function N::f(int)
and so the search/lookup stops. Now this found member function N::f(int)
has a parameter of type int
but we're passing an argument of type M
and since there is no implicit conversion from M
to int
, this call fails.
To solve this, use the scope operator::
to tell the compiler that you want to call the global function f
as shown below:
struct N {
M m;
void f(int i) {
//------vv---------->use the scope operator :: to call the global version
::f(m);
}
};