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
Leave a Reply