Function-Overloading
Function-Overloading
Example
#include <iostream>
using namespace std;
void sum(int a, int b)
{
cout << "sum = " << (a + b);
}
Void sum(double a, double b)
{
cout << endl << "sum = " << (a + b);
}
// Driver code
int main()
{
sum(10, 5);
sum(5.3, 5.2);
return 0;
}
Output
sum = 15
sum = 10.5
Output
sum = 12
sum = 15
#include <iostream>
using namespace std;
void myFunction();
void myFunction(int);
int main()
{
myFunction();
int num;
cout<<"Enter a number: ";
cin>>num;
myFunction(num);
cout<<endl;
return 0;
}
void myFunction()
{
cout<<"---Welcome to the Portal---\n";
}
void myFunction(int x)
{
cout<<"You entered: "<<x;
}
The function funcExp has seven parameters. The parameters z, u, v, and w are default
parameters. If no values are specified for z, u, v, and w in a call to the function funcExp, their
default values are used.
Suppose you have the following statements: int a, b; char ch; double d;
The following function calls are legal:
1. funcExp(a, b, d);
2. funcExp(a, 15, 34.6, 'B', 87, ch);
3. funcExp(b, a, 14.56, 'D');
In statement 1, because the value of z is omitted, all other default values must be omitted.
In statement 2, because the value of v is omitted, the value of w should be omitted, too.
The following are illegal function prototypes with default parameters:
1. void funcOne(int x, double z = 23.45, char ch, int u = 45);
2. int funcTwo(int length = 1, int width, int height = 1);
3. void funcThree(int x, int& y = 16, double z = 34);
In statement 1, because the second parameter z is a default parameter, all other parameters
after z must be default parameters.
In statement 2, because the first parameter is a default parameter, all parameters must be
the default parameters.
In statement 3, a constant value cannot be assigned to y because y is a reference
parameter.
#include<iostream>
using namespace std;
int volume(int l = 1, int w = 1, int h = 1);
void funcOne(int& x, double y = 12.34, char z = 'B');
int main()
{
int a = 23; double b = 48.78; char ch = 'M';
cout << " a = " << a << ", b = " << b << ", ch = " << ch << endl;
cout << " Volume = " << volume() << endl;
cout << " Volume = " << volume(5, 4) << endl;
cout << " Volume = " << volume(34) << endl;
cout << " Volume = " << volume(6, 4, 5) << endl;
funcOne(a); funcOne(a, 42.68); funcOne(a, 34.65, 'Q');
cout << " a = " << a << ", b = " << b << ", ch = " << ch << endl;
return 0;
}
int volume(intl,intw,inth)
{
returnl*w*h;
}
void funcOne(int &x,double y,char z)
{
x =2*x;
cout<<"x="<<x<<",y=" <<y<<",z="<<z<<endl;
}