Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix an "ambiguous" function call?

Tags:

I'm working on a C++ program for class, and my compiler is complaining about an "ambiguous" function call. I suspect that this is because there are several functions defined with different parameters.

How can I tell the compiler which one I want? Aside from a case-specific fix, is there a general rule, such as typecasting, which might solve these kinds of problems?

Edit:

In my case, I tried calling abs() inside of a cout statement, passing in two doubles.

cout << "Amount is:" << abs(amountOrdered-amountPaid);

Edit2:

I'm including these three headers:

#include <iostream> #include <fstream> #include <iomanip>  using namespace std; 

Edit3:

I've finished the program without this code, but in the interest of following through with this question, I've reproduced the problem. The verbatim error is:

Call to 'abs' is ambiguous.

The compiler offers three versions of abs, each taking a different datatype as a parameter.

like image 450
Moshe Avatar asked Sep 26 '11 01:09

Moshe


People also ask

What is an 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.

How do you remove ambiguous error in C++?

You can resolve ambiguity by qualifying a member with its class name using the scope resolution ( :: ) operator. The statement dptr->j = 10 is ambiguous because the name j appears both in B1 and B2 .

How does C++ resolve a function call?

As such, we move on to the second tiebreaker. If the first tiebreaker doesn't settle it, then C++ prefers to call non-template functions over template functions. This is the rule that decides the winner in our example; viable function 1 is a non-template function while viable function 2 came from a template.

What is ambiguous method call in Java?

This ambiguous method call error always comes with method overloading where compiler fails to find out which of the overloaded method should be used.


1 Answers

What's happened is that you've included <cstdlib> (indirectly, since it's included by iostream) along with using namespace std;. This header declares two functions in std with the name abs(). One takes and returns long long, and the other returns long. Plus, there's the one in the global namespace (that returns int) that comes from <stdlib.h>.

To fix: well, the abs() that takes double is in <cmath>, and that will actually give you the answer you want!

like image 149
Matt K Avatar answered Sep 28 '22 11:09

Matt K