Reputation: 175
I have a function fun()
I wish to overload in the same scope. As per the rules of overloading, different order of arguments should allow for the overloading of the function as mentioned here.
The Code:
#include "iostream"
using namespace std;
void fun(int i, float j)
{
cout << "int,float";
}
void fun(float i, int j)
{
cout << "float,int";
}
int main()
{
fun(20,20);
}
Error:
error: call of overloaded ‘fun(int, int)’ is ambiguous
15 | fun(20,20);
Question:
Had there been only one function with argument fun(int, float), that would have been called as the best match, so why does it throw error in this case.
Upvotes: 1
Views: 2623
Reputation: 56
The reason why you are facing this error is due to the data type of the arguments you have provided In this case
fun(20,20);
which are both int, int.
A correct function call in this scenario would be,
fun(20,20.0);
or
fun(20.0,20);
(edit) as mentioned by Ivan Vnucec it would be better to explicitly call the function with arguments that are float instead of double so call it in this way:
fun(20,20.0f);
or
fun(20.0f,20);
Upvotes: 2
Reputation: 268
You give two integers, so the compiler have to convert one into a float, but which function shall be taken?
int main()
{
fun(20.0,20);
fun( 20, 20.0);
}
these calls makes the compiler happy, since you tell which function shall be taken.
Upvotes: 2