BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Function Overloading – Call of Overloaded Function is ambiguous

Last Updated: September 12, 2017 by Chaitanya Singh | Filed Under: Learn C++

In the Function overloading tutorial, we have seen how to overload a function by providing the same function with different number, type or sequence of arguments. However some of you may get an error, particularly when dealing with floats. Lets take an example to understand what I am talking about.

Function overloading example, when call to function is ambiguous

In this example we are overloading a function sum. While overloading we gave different types of arguments in both the functions so its a valid case of overloading but still we get compilation error in this program.

#include<iostream>
using namespace std;
int sum(int a,int b){
   return a+b;
}
int sum(float a, float b){
   return a+b;
}
int main(){
   cout<<sum(1.3, 2.7);
   return 0;
}

Output:

error: call to 'sum' is ambiguous

The reason is that while calling sum function we passed floating point value to function, assuming that compiler would treat them as float but the fact is that the compiler treat all the floating points numbers as double until unless you specially specify them as float by providing a “f” suffix at their end.

So to solve the issue we need to suffix the arguments with “f” like this:

#include<iostream>
using namespace std;
int sum(int a,int b){
   return a+b;
}
int sum(float a, float b){
   return a+b;
}
int main(){
   cout<<sum(1.3f, 2.7f);
   return 0;
}

Output:

4
❮ PreviousNext ❯

Top Related Articles:

  1. Function Overriding in C++
  2. Pointers in C++
  3. goto statement in C++ with example
  4. Passing Array to Function in C++
  5. Inheritance in C++

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap