Reputation: 94
so I faced this question in an interview and got very confused about the overloading rules, could you point me to the explication at compile time.
The overloaded function:
int mult(int a, int b)
{
cout<<"int "; return a*b;
}
long mult(long a, long b)
{
cout<<"long "; return a*b;
}
float mult(float a, float b)
{
cout<<"float "; return a*b;
}
And then the calls:
long m = mult(5.2,7);
cout<<"result "<<m<<endl;
float f = mult(5,7.2);
cout<<"result "<<f<<endl;
What are the rules for the choice between the functions?
Upvotes: 1
Views: 65
Reputation: 14705
You have a good description at https://en.cppreference.com/w/cpp/language/overload_resolution
What is happening here is that mult is selected based on the least amount of conversions.
long m = mult(5.2,7);
long m
is completely irrelevant. This call is mult(double, int)
so now to find the best fit for this function the rules say find the function with the least amount of conversions applied. (See Best viable function).
This amounts to mult(int, int)
only needing one conversion. All the other functions needs two implicit conversions to match.
The same argument is also true for the second call.
These rules can easily make a call ambiguous, for instance
If you added
float mult(int a, float b);
into the mix, your program doesn't compile. The call
float f = mult(5, 7.2);
Is also one implicit conversion away, the same as the mult(int, int)
function hence ambiguous.
Upvotes: 3