Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does calling an overloaded function with arguments that don't match still work

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;
}
like image 612
Cătălina Sîrbu Avatar asked Dec 13 '22 09:12

Cătălina Sîrbu


1 Answers

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.

like image 177
François Andrieux Avatar answered Dec 15 '22 21:12

François Andrieux