What is Function Overloading in C++?

- August 04, 2018

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<iostream.h>
#include<canio.h>
using namespace std;
   int cube(int x)
   {
      return x * x * x;
   }
double cube(double x)
   {
      return x * x * x;
   }
main()
 {
    clrscr();
    cout<<"Cube of 4.2 is: "<<cube(4.2)<<endl;
    cout<<"Cube of 6 is: "<<cube(6)<<endl;
    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.

Cpp function overloading example

Function Overloading Example Program

#include<iostream.h>
#include<canio.h>
using namespace std;
void square(void)
  {
      for(int u=1; u<=4; u++)
      {
        for (int i=1; i<=4; i++)
        cout<<"*";
        cout<<endl;
     }
  }
void square(char x)
  {
      for(int u=1; u<=6; u++)
      {
        for (int i=1; i<=6; i++)
        cout<<"x";
        cout<<endl;
     }
  }
void square(char x, int n)
  {
      for(int u=1; u<=n; u++)
      {
        for (int i=1; i<=n; i++)
        cout<<x<<" ";
        cout<<endl;
     }
  }
main()
  {
    clrscr();
    square();
    cout<<endl;
    square('C');
    cout<<endl;
    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

Leave your reply.
EmoticonEmoticon

 

Start typing and press Enter to search