Thursday 23 February 2012

Function overloading


Function overloading


When several function declarations for a single function name in the same scope, the name is said to be overloaded. C++ allowed functions to have the same name if it can distinguish them by their number and types of arguments.
Example:
Float  mult(int a, int b);
Float  mult(float x, float y);


In this case mult function have two arguments  but one mult function have int argumants and other have float arguments.
This is known as function overloading.
Function overloading is a function having several definations that are different in respect of number  of arguments passed or datatypes of  the arguments.


Need for function overloading


While using different function for different situation we need to decide upon which function should be executed . but using function overloading compiler automatically decides which function should executed. It will not only reducing the number of if else but also make the code execute faster as so many caoparisons are eliminated.
For example:

Char choice;
Cout<< “its hot or cold? (Y|N)”;
cin>> choice:
if(choice==’Y’)
Hot();
Else if(choice==’n’)
Cold();
Else
Cout<<”\nwrong choice\n”;
.
.
Declaration and definition


The key to function overloading  is a function’s argument list which is also known as the function signature.
If two functions are having same number and types of argument s in the same order , they are said to have the same signature even if they are using distinct variable names, it does not matter. For example:

Void square(int a);
Void square(flaot x);


For declaring a function overload there must same name but different signatures.
After declaring a function  definition of function is done separately.

Void square(int a)
{ cout<<”integer” <<a<<” square is “ <<a*a<<”\n”;}
And 
2) Void square(float x)
{ cout<<”float”<<x<<”square is” <<x*x<<”\n”;}


Calling overloaded function
Overloaded functions are called just like other functions. for example:
Square(14.54F);    it will calls the function number 2 discussed above
Sometimes there might be ambiguity between float and double values or say int or long.to avoid this ambiguity constant suffixes must be provided (F, L,U,UL etc) to distinguish between such values.
An ordinary floating constant(321.89)has the double type, while adding F suffix(321.89F)  makes it’s a float.

No comments:

Post a Comment