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

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 ❯

Leave a Reply Cancel reply

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

C++ Tutorial

  • C++ Tutorial
  • First C++ Program
  • C++ Variables
  • C++ Data types
  • C++ Operators

Flow Control

  • C++ If-else
  • C++ Switch Case
  • C++ for loop
  • C++ while loop
  • C++ do-while loop
  • C++ Continue
  • C++ break
  • C++ goto

Functions

  • C++ Functions
  • Default Argument in Function
  • C++ Recursion

Arrays

  • C++ Arrays
  • Multidimensional Arrays
  • C++ Array to Function
  • C++ Strings

Pointers

  • C++ Pointers
  • "this" Pointer

OOPs Concepts

  • C++ OOPs
  • C++ Constructor
  • C++ Destructor
  • C++ Structure
  • Struct and Function
  • C++ Enum
  • C++ Inheritance
  • C++ Polymorphism
  • C++ Function Overloading
  • C++ Function Overriding
  • Function Overloading vs Overriding
  • C++ Virtual Function
  • Encapsulation
  • Abstraction
  • C++ Interfaces
  • Friend Class and Function

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap