Query about function overloading

Viewed 54

When using function with same name, parameter list must differ(either in type of parameter or number of parameters used). I was just practicing with this concept. I wrote the following code.

   #include <iostream> 
    int myFunction(int n)
   { 
    return 2*n;
   }
    float myFunction(float n)
   { 
    return 3*n;
   }
    int main()
   {
    int x=myFunction(3);
    std::cout << x; 
    return 0;
   }  
    

I thought I will get error because compiler will get confused which myFunction to use because I directly pass the value 3 without storing it in a particular type of variable . But I got output 6. So I tried the following code.

   #include <iostream> 
    int myFunction(int n)
   { 
    return 2*n;
   }
    float myFunction(float n)
   { 
    return 3*n;
   }
    int main()
   {
    float x=myFunction(3.3);
    std::cout << x; 
    return 0;
   }  
    

As previous one worked fine, I thought this will work fine too, as 3.3 is not integer so it's clear which one to call, but this time I got compiler error saying it's ambiguous.

So my doubt is why first code worked but not second one.

3 Answers

The process of selecting the overload during a call is called overload resolution. Given the types of the arguments, the compiler selects the best viable function from the list of candidates - the one that can be invoked with the least amount of promotions and implicit conversions.

In the first case the first one myFunction(int) requires 0 conversions for an int argument (3), and the second one requires one conversion (int -> float), so the first one is selected as the best candidate.

In the second case a double argument (3.3) requires a conversion to either int or float, so there is no clear winner and thus the call is ambiguous.

The fix could be to use a float argument (3.3f) or change myFunction(float) to myFunction(double).

Literals have types too. As integer literal 3 is of type int, then the 1st overload is selected.

As floating point literal 3.3 is of type double (but not float; with the suffix f like 3.3f the type is determined as float), the calling is ambiguous because it could convert to both int and float implicitly.

try this:

int x=myFunction(int(3));

float x=myFunction(float(3.3));
Related