Sunday, November 30, 2008

Function Overloading

‘Overloading’ means a thing is having one name but distinct meanings. C++ supports two types of overloading
1. Function Overloading
2. Operator Overloading

Function overloading means one function name can have different meanings. And it can perform distinct tasks. But now the question is, how it can be done ?
It is done very intelligently, just providing different argument lists which is also known as function signature. The overloaded function is selected on the basis of following criteria –
Number of arguments
Type of arguments
Order of arguments

Important : - return type of function doesn’t take participate in overloading.

This information is available to compiler at compile-time itself , hence called early binding or static binding or static linking. It is also known as Compile-time polymorphism.


For example :
A. float sum ( int a, int b)
B. float sum (float a, float b)
C. float sum (float a, float b, float c)

That is , in A sum() is taking two int arguments , in B sum is taking two float arguments while in C sum() is taking three float arguments.

Declaration and Definition

void printMe(int a)
void printMe(float f)
void printMe(double d)
void printMe(char c)

After declaration of overloading functions, we have to define them in following manner.

void printMe(int a)
{
cout<<”I am “<<a<<endl;

}

void printMe(double d)
{
Cout<<”I am “<<d<<endl;
}

void printMe(char c)
{
Cout<<”I am “<<c<<endl;
}

Now you can understand how easy to work with overloading functions.

No comments: