Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




Function Overloading

In it we can use the same function name to create functions that perform different tasks. By using this concept we can create different functions that have same name but take different arguments. The correct function that will be invoked for a particular function call depends upon the number, types and sequence of the arguments but the return type of the function does not matter for selection.

For example (C++):

//Declarations

int add (int a, int b); //Prototype 1
int add (int a, float b); //Prototype 2
float add (float a, float b); //Prototype 3
int add (int a, int b, int c); //Prototype 4

//Function Calls

cout<<add(5,10); //Uses prototype 1
cout<<add(2,10,3); //Uses prototype 4
cout<<add(6,2.75); //Uses prototype 2
cout<<add(3.75,4.5); //Uses prototype 3



------------------------------------------------------------


The selection of a particular function for a particular function call is done by using following steps:



1.
First
of all the compiler tries to make exact match on the basis of number,
sequence and data types of arguments. If exact match is found then that
function is used otherwise next step is used.



2.
If exact match is
not found, then the compile applies the following conversions or
promotions to select the appropriate function:



– char, unsigned char, short to int.

– float to double
etc.

These
conversions or promotions are done under the same category, like char
and int belong to same category, float and double belong to same
category etc. If it works then ok, otherwise next step is used.


3.
If
the above two steps fail, then compiler tries to make built-in
comparisons to find the appropriate match. Such conversions can be:


– int to double and vice versa.

– int to float and vice versa.


These conversions are done under different categories like if we try to
convert int to double then both are falling under different category.
If using this unique match is found then ok, but if multiple matches
are found then the complier will generate error message.



4.
If all the above steps fail then
compiler will try to find the match by using used-defined conversions
along with promotions and built-in conversions.

The example of function overloading in case of C++ is given below:


Share this article   |    Print    |    Article read by 3125 times
Author:
Rohit kakria
I am software developer, moderator of xpode.com
Related Articles:
Related Interview Questions: No related interview question