Visit Site
Consider a following c++ examples
int areaofsquare(int s)
{
return s*s;
}
int areaofrectangle(int a,int b)
{
return a*b;
}
int main()
{
int x=0,y=0,area;
x=5;
if(x>0 && y==0) area=areaofsquare(x);
x=5;y=6;
if(x>0 && y==0) area=areaofrectangle(x,y);
cout<<"Area of Box = "<<area<<endl;
return 0;
}
In the above example two functions are doing a similar job but their names are different and they have to be called with different names only when they are called. Now if we write the above code as follows.
int areaofbox(int s)
{
return s*s;
}
int areaofbox(int a,int b)
{
return a*b;
}
int main()
{
int x=0,y=0,area;
x=5;
area=areaofbox(x);
cout<<"Area of Box = "<<area<<endl;
x=5;y=6;
area=areaofbox(x,y);
cout<<"Area of Box = "<<area<<endl;
return 0;
}
Here we are using the same function name and it is being used on the basis of number of parameters passed. Notice that in this we have not written the if check condition. You may feel that this is quite trivial and we might even use different function names in this example, but it is much more convenient and straight forward to use similar names and let the computer select the appropriate function required on the basis of parameters.
This is also useful when datatypes int, float, double etc are to be handled with same function name and you need to use them as per user given values. for e.g.
float convert(float);
int convert(int);
double convert(double);
would be required to write independently even though their tasks are similar but memory size needs for variables are different.
In nutshell:
We overload functions so that we can leave the task of selecting the right function to be used to the compiler on the basis of function parameters rather than calling functions of different names based on our own condition formation.