-4

I'm learning about function overloading in C++ and I was having a doubt on function matching. Running below code I was getting error C2668: 'function' : ambiguous call to overloaded function.

The reson why I got error was clearly answered in this link. The number 1.2 and 2.2 are type double.Although there is one more doubt which I have and was not answered there. When I try to call function(1.2,2) or function(1,2.2) it is printing as "int function". Why it is not giving error same as above.

CODE:

  void function(int y,int w)
    {
      printf("int function");

    }


 void function(float y,float w)
  {
    printf("float function");
  }


int main()
 {
   function(1.2,2.2);
   return 0;
 }
Yogesh Tripathi
  • 703
  • 5
  • 16

1 Answers1

1

When I try to call function(1.2,2) or function(1,2.2) it is printing as "int function". Why it is not giving error same as above.

Because according to the rules of overload resolution void function(int y,int w) is a better match than void function(float y,float w) and therefore there is no ambiguity.

Calls function(1.2,2) and function(1,2.2) both have one argument that is an int and is the exact match with one of the arguments of void function(int y,int w), and so only one type conversion is required, double to int. void function(float y,float w) on the other hand requires two conversions int to float and double to float, and this is why int overload is used.

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37