I was a bit surprised finding out this feature in C++, and I didn’t expect it to happen.
Here is the code:
struct XY {
int x,y;
XY(int v) : x(v), y(v) {}
};
bool test1(const XY &pos){
return pos.x < pos.y;
}
bool test1(int x, int y){
return x < y;
}
void functest(){
int val = 5;
test1(val);
}
So I can call a function with integer parameter, whether or not such overload exists, it will use the XY type function because it has a constructor of that same type! I don’t want that to happen, what can I do to prevent this?
Make the
XYconstructor explicit:This will disallow implicit conversions from
inttoXY, which is what is happening when you call the single-parametertest1function.