Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does function overloading generate an ambiguous error in C++?

Tags:

In the following code snippets, In function call f(1), 1 is a literal of type int and in first function void f(double d) argument type is double and second function void f(short int i) argument type is short int.

Here 1 is an int type not a double type, then Why does compiler generated ambiguous error?

#include <iostream>
using namespace std;

void f(double d)  // First function
{
    cout<<d<<endl;
}

void f(short int i) // Second function
{
    cout<<i<<endl;
}

int main()
{
    f(1); // 1 is a literal of type int
    return 0;
}
like image 561
Jayesh Avatar asked Sep 21 '17 06:09

Jayesh


People also ask

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.

How can C call to an overloaded function be ambiguous?

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.

Why is function overloading not allowed in C?

Function overloading is a feature of Object Oriented programming languages like Java and C++. As we know, C is not an Object Oriented programming language. Therefore, C does not support function overloading.

What is ambiguous error in C++?

Access to a base class member is ambiguous if you use a name or qualified name that does not refer to a unique function or object. The declaration of a member with an ambiguous name in a derived class is not an error. The ambiguity is only flagged as an error if you use the ambiguous member name.


1 Answers

Because, as your comment notes, 1 is a literal of type int.

To the compiler, an implicit conversion of int to short int is equally as valid as an implicit conversion of int to double (cf. the C++ language standard, §13.3).

Thus, because the compiler can't decide between the double and short int overloads, it gives up and issues a diagnostic.

Note that the magnitude of the function parameter doesn't matter: just the type.

(It would be annoying if the compiler chose, at runtime, the short int overload if the calling argument was appropriate, and the double one in other instances.)

like image 156
Bathsheba Avatar answered Sep 28 '22 05:09

Bathsheba