I'm trying
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; }
I get an error error like..
error C2668: 'function' : ambiguous call to overloaded function
and when I try to call function(1.2,2)
or function(1,2.2)
it is printing as "int function"
Please clarify when will the function(float y,float w)
be called?
Answer: If two or more functions have the same name and function signature, the call to an overloaded function can be unclear. Explanation: Function overloading ambiguity occurs when the compiler is unable to decide which of the overloaded functions should be invoked first.
Function Overloading and float in C++ If the compiler can not choose a function amongst two or more overloaded functions, the situation is -” Ambiguity in Function Overloading”. The reason behind the ambiguity in above code is that the floating literals 3.5 and 5.6 are actually treated as double by the compiler.
You cannot override one virtual function with two or more ambiguous virtual functions. This can happen in a derived class that inherits from two nonvirtual bases that are derived from a virtual base class.
Look at the error message from gcc:
a.cpp:16: error: call of overloaded ‘function(double, double)’ is ambiguous a.cpp:3: note: candidates are: void function(int, int) a.cpp:9: note: void function(float, float)
A call to either function would require truncation, which is why neither is preferred over the other. I suspect you really want void function(double y,double w)
. Remember that in C/C++, the default floating-point type for literals and parameter passing is double, NOT float.
UPDATE
If you really don't want to change the function signature from float to double, you can always use literals that are typed as float. If you add the suffix f to the floating point numbers, they will be typed float.
Your examples would then be function(1.2f, 2f)
and function(1, 2.2f)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With