Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is Function Overloading in C++?


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
When an overloaded function is called for executing, C++ compiler selects the proper function by checking the number of perameters, theit data types and order in function call. The compiler marks a proper function name for each function, sometimes reffered to as name decoration. In this way, a proper overloaded function is called for execution whose return type and perameters are matched with the parameters given in the function call. The compiler uses only the parameter lists to distinguish between functions of the same name.

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



This post first appeared on Programming Explain, please read the originial post: here

Share the post

What is Function Overloading in C++?

×

Subscribe to Programming Explain

Get updates delivered right to your inbox!

Thank you for your subscription

×