Declaring multiples functions with the same name but with different set of parameters and return data types is called function overloading.The functions with same names must be differ in one of the following ways:
- Types of the parameters
- Number of parameters
- Sequence of parameters
Example of Overloaded Function
The following C++ program explains the concept of function overloading.#include
#include
using namespace std;
int cube(int x)
{
return x * x * x;
}
double cube(double x)
{
return x * x * x;
}
main()
{
clrscr();
cout cout getch();
}
In this program, two functions with the same name are defined before the main() function. When the function "cube" is called by passing 4.2 value then the function "cube" will be executed that has argument of double type. Similarly, when the function cube is called by pessing integer value "6" then the function cube that has int type argument will be executed.
Function Overloading Example Program
#include
#include
using namespace std;
void square(void)
{
for(int u=1; u {
for (int i=1; i cout cout }
}
void square(char x)
{
for(int u=1; u {
for (int i=1; i cout cout }
}
void square(char x, int n)
{
for(int u=1; u {
for (int i=1; i cout cout }
}
main()
{
clrscr();
square();
cout square('C');
cout square('f', 12);
getch();
}
Output of the Program
If you execute the above program, the output will be as follows:****
****
****
****
CCCCCC
CCCCCC
CCCCCC
CCCCCC
CCCCCC
CCCCCC
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
****
****
****
CCCCCC
CCCCCC
CCCCCC
CCCCCC
CCCCCC
CCCCCC
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff
ffffffffffff