Good day, community!

Just started learning with ++, so don't be hard on you.

I read the book "Programming in C ++. Dirk Henkemans, Mark Lee." It gives the following example of function overloading:

int add (int a, int b) { return a + b; } float add (float a, float b) { return a + b; } int main(void) { cout << add(5,3); cout << add(5.5, 4.7); return } 

However, my code does not compile. The compiler does not understand this construction, and swears: call of overloaded `add (double, double) 'is ambiguous . How is it going?

In some forums, they write that the c ++ compiler cannot determine whether an integer is related to an int or float.

    2 answers 2

    because 5.5 is double . and it cannot be converted to float. Therefore, either write the implementation with double , or call it like this:

      cout << add(5.5f, 4.7f); 

    UPD:

    Why double ? all according to the standard - 2.14.4, subparagraph 1, where it is said that if there is a real number and it does not have a suffix (one of f , F , l , L ), then it will be double.

    • clear, thank you - teanYCH

    In general, the overloading of functions in this form is a bit clumsy. After all, what if you need function overloading for 3-4 simple types? Often focus on the use of template functions:

     template<class Res, class A, class B> Res s(A a, B b) { return a+b; } 

    Using:

     cout<<s<double>(1,5.7)<<endl <<s<int>(1,5.7)<<endl;