This question already has an answer here:
I'm overloading the function add()
, but when I used the float
datatype it is showing an error. However, when I change it to double
, then it's working fine. Why is float
causing the error?
Code is:
#include <iostream>
using namespace std;
class students{
private:
int i;
float f;
public:
void add(int b){
i=b;
cout << "First Int: " << i;
}
void add(float c){
f=c;
cout << "Second Int: " << f;
}
};
int main(){
students obj;
obj.add(9);
obj.add(5.5);
}
Errors:
In function 'int main()':
[Error] call of overloaded 'add(double)' is ambiguous
[Note] candidates are:
[Note] void students::add(int)
[Note] void students::add(float)
5.5
is adouble
, but none of your functions take adouble
argument. So, the compiler gets confused on whether to call the function with theint
parameter, or the function with thefloat
parameter. So, you get a an error saying it is ambiguous.That is why when you changed the function to have a
double
parameter, the error no longer came, because now there is a function which can take adouble
argument, and thus there is ambiguity there.You can also fix the problem by calling the function as
Adding the
f
after a number makes it to a float.Let's look at the C++ Standard
§ 2.13.4
( Sorry for posting all of it, but you can learn more about
float
s this way )