Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange ambiguous call to overloaded function error

Tags:

c++

visual-c++

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?

like image 867
james raygan Avatar asked May 17 '13 05:05

james raygan


People also ask

Can a call to an overloaded function be ambiguous options the?

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.

What is the reason of ambiguity while overloading display function?

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.

What is ambiguous function call?

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.


1 Answers

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).

like image 136
ggcodes Avatar answered Oct 07 '22 03:10

ggcodes