In a program there can be many functions with different name. However, some functions conceptually perform the same task on objects of different types and numbers. In such a case it is convenient to give them same name. When the same name is used for different operation, it is called function overloading. When an overloaded function is called the function with matched arguments is invoked.
Examples of overloaded functions are as follows:
void display(); //function with no arguments
void display(int); //function with one int argument
void display(float); //function with one float argument
void display(int, float) //function with one int and
//one float argument
A Complete Example to demonstrate the function overloading is as follows:
Source Code:
//function overloading
#include<iostream>
using namespace std;
int max(int, int);
long max(long, long);
float max(float, float);
char max(char, char);
int main()
{
int i1 = 12, i2 = 22;
cout<<"Greater is "<<max(i1, i2)<<endl;
long l1 = 400000, l2 = 380000;
cout<<"Greater is "<<max(l1, l2)<<endl;
float f1 = 34.04, f2 = 54.455;
cout<<"Greater is "<<max(f1, f2)<<endl;
char c1 = 'f', c2 = 'F';
cout<<"Greater is "<<max(c1, c2)<<endl;
return 0;
}
int max(int i1, int i2)
{
return(i1 > i2 ? i1 : i2);
}
long max(long l1, long l2)
{
return(l1 > l2 ? l1 : l2);
}
float max(float f1, float f2)
{
return(f1 > f2 ? f1 : f2);
}
char max(char c1, char c2)
{
return(c1 > c2 ? c1 : c2);
}
Sample Run
Greater is 22
Greater is 400000
Greater is 54.455
Greater is f
Examples of overloaded functions are as follows:
void display(); //function with no arguments
void display(int); //function with one int argument
void display(float); //function with one float argument
void display(int, float) //function with one int and
//one float argument
A Complete Example to demonstrate the function overloading is as follows:
Source Code:
//function overloading
#include<iostream>
using namespace std;
int max(int, int);
long max(long, long);
float max(float, float);
char max(char, char);
int main()
{
int i1 = 12, i2 = 22;
cout<<"Greater is "<<max(i1, i2)<<endl;
long l1 = 400000, l2 = 380000;
cout<<"Greater is "<<max(l1, l2)<<endl;
float f1 = 34.04, f2 = 54.455;
cout<<"Greater is "<<max(f1, f2)<<endl;
char c1 = 'f', c2 = 'F';
cout<<"Greater is "<<max(c1, c2)<<endl;
return 0;
}
int max(int i1, int i2)
{
return(i1 > i2 ? i1 : i2);
}
long max(long l1, long l2)
{
return(l1 > l2 ? l1 : l2);
}
float max(float f1, float f2)
{
return(f1 > f2 ? f1 : f2);
}
char max(char c1, char c2)
{
return(c1 > c2 ? c1 : c2);
}
Sample Run
Greater is 22
Greater is 400000
Greater is 54.455
Greater is f
No comments:
Post a Comment