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 XY constructor explicit:
explicit XY(int v) : x(v), y(v) {}
This will disallow implicit conversions from int to XY, which is what is happening when you call the single-parameter test1 function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With