Sunday, November 30, 2008

Function Overloading 2

How to call Overloaded Functions

printMe(108);
printMe(3.14F);
printMe(420.12009);
printMe(‘k’);

Note : suffix F or f has to be used with float without F or f it will be treated as double

Function Overloading and Ambiguity

If compiler is not able to choose between two or more overloaded function , it leads to ambiguity. Ambiguous statements are errors and programs containing ambiguity will not compile.
Main cause of ambiguity is C++’s automatic type conversions.
C++ automatically attempts to convert the arguments used to call a function into the type of arguments expected by the function.

For example:
Suppose if function declration is
int showMe(double d);

and if we call it like

showMe(‘x’); // not an error , conversion occurred

So above statement will not show any error because C++ automatically converts the character ‘x’ into its double equivalent.

Now consider this program.




#include

float exposeMe(float f);
double exposeMe(double d);

main()
{
cout<<”Secret no : “<<exposeMe(42.4); // not ambiguous, calls exposeMe( double) : 1
cout<<”\nAnother Secret number : “<< exposeMe(100); // : 2
return 0;

}

float exposeMe(float f)
{
return f;

}

double exposeMe(double d)
{
return d;
}

Here, exposeMe() is overloaded it can accept either float or double type data. In 1 exposeMe(double) is called, because all floating point constants in C++ are automatically of type double if suffix f or F is not there. Hence this call is not ambiguous. However function 2 exposeMe(100) is called , it leads to ambiguity because compiler has no way to know whether it should be converted to a float or to a double. This causes an error message to be displayed , and the program will not compile.

Another example of ambiguity



#include

float exposeMe(unsigned char c);
double exposeMe(char c);

main()
{
cout<<”Reveled Character is : “<<exposeMe(‘x’);
cout<<”\nAnother Reveled Character is : “<< exposeMe(999); // : 2
return 0;

}

float exposeMe(unsigned char c)
{
return c - 1;

}

double exposeMe(char c)
{
return c + 1;
}

In C++, unsigned char and char are not inherently ambiguous. However, when exposeMe(99) is called the compiler has no way to know which function to call. That is, whether 99 should be converted into a char or an unsigned char?



To be continued….

1 comment:

Unknown said...

Thanks for the nice illustration.