Function Overloading
when i compile the following code about function overloading the compiler throws the error message:
" ambiguity between 'abso(int)' and 'abso(float)' "
#include<iostream.h>
#include<conio.h>
int abso(int i);
long abso(long l);
float abso(float f);
main()
{
clrscr();
abso(-10);
abso(19L);
abso(0.5);
getch();
}
int abso(int i)
{
cout <<"IN INT ABSO FUNCTION--";
cout << i ;
}
float abso(float f)
{
cout <<"IN FLOAT FUNCTION";
cout << f;
}
long abso(long l)
{
cout <<"IN LONG FUNCTION--";
cout << l;
}
but the program compiles and runs well if i remove the float part and overload int and long only...why wont the compiler overload when i int and float together?
i use the borland turboC++ compiler... can u plz explain why this is happening?
# 1 Re: Function Overloading
Please place your code snippets in code forum bbcode tags.
I believe that is because 0.5 is a double literal, not a float literal. As such, it does not exactly match any of the parameters of the overloaded abso() functions, but all of them are suitable candidates for matching.
One solution is to overload abso() for a double parameter. Another solution is to use 0.5f instead of 0.5. Depending on what you actually want to do, perhaps a function template would be even more appropriate.
Also, note that you should use <iostream> instead of <iostream.h>, and that main() should be explicitly declared as returning an int. <conio.h> is non-standard and probably not needed here.
# 2 Re: Function Overloading
Also you're not returning anything from any of the abso functions. You should have gotten compiler errors about this too. Overloading doesn't require you to change the return type of the functions, just the parameters. Changing the return type is optional.
# 3 Re: Function Overloading
You can also implement a template function instead of writing a function for different types:
template<typename T>
T abso( const T& value )
{
return value > 0 ? value : -value;
}
# 5 Re: Function Overloading
Also you're not returning anything from any of the abso functions. You should have gotten compiler errors about this too. Overloading doesn't require you to change the return type of the functions, just the parameters. Changing the return type is optional.
no no errors just warnings :D