#include <iostream>
using namespace std;
class Sample{
public:
int sum(int a, int b)
{
cout << "int sum";
return a+b;
}
float sum(float a, float b)
{
cout << "float sum" ;
return a+b;
}
};
int main()
{
cout<<"Hello World";
Sample s1;
s1.sum(5.5, 5);
return 0;
}
In above code, when sum function get called always run sum function with int parameter. I could not understand why, also it doesn’t even throws any error.
But when I change my function call to following:
s1.sum(5.5f, 5)
which gives me error:
"error: call of overloaded ‘sum(float, int)’ is ambiguous"
and that is understandable.
Can anyone please explain me this behavior?
>Solution :
In this case:
s1.sum(5.5, 5);
The 2nd argument is an int
and the 1st is a double
and convertible to int
and hence the 1st overload is called (regarding the 2nd overload, none of the arguments match its parameters and is therfore an inferior match).
On the other hand in this case:
s1.sum(5.5f, 5)
The 1st argument is a float
and the 2nd is an int
. Both overloads match 1 argument and require conversion for the other and hence the ambiguity error.