Function Overloading


Overloading means using same thing for different purpose.
The process of using same function for different purpose is known as Function Overloading.
In Function Overloading you can create more then one function having same name but with
(1) Different Number of Arguments
(2) Different Data Types
(3) Different Return Type
When you call the function, appropriate version of the function is invoked at compile time depending upon the number and type of arguments.
Function overloading is the best example of compile time polymorphism.

     

Example:
#include<iostream.h>
void main()
{
int a , b, c;
int sum (int p, int q);
int sum (int p, int q, int r);
cout <<"Enter Three Numbers:"<<endl;
cin>>a>>b>>c;
cout << "Sum Of a and b is:"<<sum (a, b);
cout << "Sum of a , b and c is :"<<sum (a,b,c);
}
void sum (int p, int q)
{
return (p+q);
}
void sum (int p, int q, int r)
{
return (p+q+r);
}

In above example we create two functions having same name but having different number of arguments. When you call function with two arguments the first version of functions is called. When you call function with three arguments second version of function is called.
When overloaded functions are called compiler tries to find exact match. Exact match is that in which number of arguments and data type of the argument are same.
While calling the function if number of arguments does not match with any of the function prototype then error is generated. If Data types are not identical then type conversion is used by the compiler.

Download Projects


Download Programs