I am not able to explain why the second call (B
) doesn't give any errors as there are two char
elements, and there is no certain match for this call.
Why it is called the second one (2.
), but not the first (1.
) version?
I've noticed that there are some automatic conversions. The thing that i don't get is why 'a'
is promoted to int and 'c'
isn't.
// 1.
int fun(int a, int b)
{
return a + b;
}
// 2.
int fun(int a, char b)
{
return b - a;
}
// 3
int fun(float a, float b)
{
return a * b;
}
int main() {
// A. B. C.
cout << fun(1,0) << fun('a','c') << fun(2.f,2.f);
return 0;
}
The rules for overload resolution are complicated. In this case, the reason func('a','c')
prefers int fun(int a, char b)
is because it implies the fewest implicit conversion sequences. Looking at each case :
int fun(int a, int b)
has two arguments that are not perfect matches. It requires two promotions from char
to int
.
int fun(int a, char b)
has one exact match and one promotion from char
to int
.
int fun(float a, float b)
has two arguments that are not perfect matches that require conversions (worse than promotion) from char
to float
.
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