What is function overloading?
Function overloading means we can use the same function name to create functions that perform a variety of different tasks.
For example, we overloaded add( ) function, which further handles different data types as shown below.
Different Function Declatations
1. int add( int a, int b); //add function with 2 arguments of same type
2. int add( int a, int b, int c); //add function with 3 arguments of same type
3. float add( int a, float d); //add function with 2 arguments of different type
Function calls for defferent functions declarations above:
1. add (3 , 4); // this function call uses prototype of function declaration 1
2. add (3, 4, 5); //this function call uses prototype of function declaration 2
3. add (3 , 10.0); //this function call uses prototype of function declaration 3
C++ program which implement the Function overloading feature.
Program Code:
#include<iostream>
using namespace std;
int add( int a, int b);
int add( int a, int b, int c);
float add( int a, float d);
int main()
{
int a, b, c;
float d;
cout<<"Enter a and b and c: ";
cin>>a>>b>>c;
cout<<endl;
cout<<"Enter d : ";
cin>>d;
cout<<endl;
add (a , b);
cout<<endl;
add (a, b, c);
cout<<endl;
add (a , d);
return 0;
}
int add( int a, int b)
{
cout<<"Addition of a and b :"<<a+b;
}
int add( int a, int b, int c)
{
cout<<"Addition of a, b and c :"<<a+b+c;
}
float add( int a, float d)
{
cout<<"Addition of a and d :"<<a+d;
}
The program output is tested on www.jdoodle.com
Output:
Enter a and b and c: 1 2 3
Enter d : 12.5
Addition of a and b :3
Addition of a, b and c :6
Addition of a and d :13.5
Thanks
Mukesh Rajput
Post A Comment:
0 comments: