Search code examples
c++overloadingoverload-resolution

Ambiguity error using overload in c++


I have tried to use overload with floating and integer. When I only used the integer, the code worked fine, but when I included the floating it gave me errors. The code is the following:

#include <iostream>
using namespace std;

int calculate(int x,int y);
float calculate(float x,float y);
const int MAININT=4;

int main()
{
    int result=calculate(5,5);
    float fresult=calculate(7.5,7.5);                 LINE X
    cout << (result + MAININT + fresult);             LINE Y
    return 0;
}

int calculate(int x,int y)
{
    int result=x*y;
    return result;
}

float calculate(float x,float y)
{
    int result=x*y;
    return result;
}

By deleting LINE X and fresult from LINE Y, the code give me no errors. So I assume there must be something wrong in LINE X, but I don't understand why I get errors.

The error messages I got was :

[Error] call of overloaded 'calculate(double, double)' is ambiguous
[Note] candidates are:
[Note] int calculate(int, int)
[Note] float calculate(float, float)

I did not understand the error messages, so I didn't include them. I understand what I did wrong from the answer of songyuanyao, but next time I will include the error messages in my question from the start so it will be easier to see what I have done wrong in the code.


Solution

  • Because 7.5 is a double (see floating point literal), not a float; and implicit conversion to int or float are considered as the same ranking.

    If your suppose 7.5 as float here you could use the suffix f or F to make it a float literal. e.g.

    float fresult = calculate(7.5f, 7.5f); // 7.5f is a float literal; no ambiguity
    

    Or use explicit conversion:

    float fresult = calculate(static_cast<float>(7.5), static_cast<float>(7.5));