How function overloading works

int add(int a,int b) { cout<<"1"<<endl; return a+b; } int add(int a,char c) { cout<<"2"<<endl; return a+c; } int main() { cout<<add(10,20)<<endl; //1 cout<<add(10,'a')<<endl; //2 cout<<add('a','b')<<endl; //3 } 

in the above code, the first function calls the add (int, int) function, the second function calls the add (int, char) function. The third function call should occur as an error, but it calls the add (int, char) function. can someone explain why.

+4
source share
3 answers

there is an implicit conversion of char to int. More details here:

http://www.petebecker.com/js/js200004.html

implicit conversion:

http://en.cppreference.com/w/cpp/language/implicit_cast

+5
source

If all the parameters of one function are converted at least in the same way as other functions, and some of the parameters are converted better, this function is executed.

If not all parameters are converted, at least in the same way as other functions, and not all parameters of the last function are converted, at least in the same way as the parameters of the first function, ambiguity arises, raised in the usual case of a simple function.

+1
source

The closest match is int and char. Since char can be implicitly converted to int, it still works.

 int a = 'a'; // Returns the ascii value for 'a'. 
0
source

Source: https://habr.com/ru/post/1435344/


All Articles