I'm trying to get better grips of function overloading.
I've this test program (pardon me for my C inspired Java).
public class Test {
static void f(int x, double y)
{
System.out.printf("%d, %f",x,y);
}
static void f(double x, int y)
{
System.out.printf("%f, %d", x, y);
}
public static void main(String args[]) {
f(1, 2);
}
}
now if I call,
f(1, 2);
There is compiler error, *reference to f is ambiguous*
Why this error? Are we not calling f(int, int)
? But no such method is declared. I was expecting "no suitable method found for f" instead, but I did not get one, why?
int
is convertible to double
in all of these languages, so if only one of them were available, it would be easy: convert whichever value needs to be converted to a double
, and call the method.
But in this case, both methods are "valid" in that each would be fine on its own - but neither is "better" than the other, because in each case one argument only needs the identity int
to int
conversion, and the other needs the int
to double
conversion. So in both Java and C# it's ambiguous and will fail with a compile-time error. I'd imagine that's what it does in C++ too, but I don't know for sure. In both Java and C#, if you had also a method static void f(int x, int y)
, that would unambiguously be better than either of the other two, for that method invocation.
When in doubt, you should consult the relevant language specifications. For Java, JLS section 15.12 is the relevant part. In the C# 5 specification, it's section 7.5.
See more on this question at Stackoverflow