C++ Function Overloading

Function overloading in C++ allows us to write multiple functions having same name, so long as they have different parameters; either because their number of parameters are different or because any of their parameters are of a different data type. You can not overload a function declarations that differ only by return type.

For Example :
int getSum(int a, int b) {
  return a+b;
}

This is a simple function which takes two integer arguments and returns the sum of two integers. We can use this function to add two integers only. To add two floating point numbers we can overload getSum function ad follows:

float getSum(float a, float b) {
  return a+b;
}

Now, both above functions have same name "getSum" but their parameters are of a different data type. We can further overload getSum function to add three integers as follows :

int getSum(int a, int b, int c) {
  return a+b+c;
}

All of the three overloaded functions are different from each other either in their number of parameters or data types of parameters. We now have three version of getSum function:

  • int getSum(int a, int b); // To add two integers.
  • float getSum(float a, float b); // To add two floating point numbers.
  • int getSum(int a, int b, int c); // To add three integers.

Calling Overloaded function in C++

We can call an overloaded function like calling any other function in C++. Which version of getSum function gets called by compiler depends on the arguments passed when the function is called.If we call getSum with two integer arguments, C++ compiler will know that we want to call getSum(int, int). If we call getSum function with two floating point numbers, C++ compiler will know we want to call getSum(float, float).


C++ Function Overloading Example Program

#include <iostream>
using namespace std;

int getSum(int a, int b) {
  cout << "\nInside getSum " << a <<  " " << b;
  return a+b;
}

float getSum(float a, float b) {
  cout << "\nInside getSum " << a <<  " " << b;
  return a+b;
}

int getSum(int a, int b, int c) {
  cout << "\nInside getSum " << a <<  " " << b << " " << c;
  return a+b+c;
}

int main(){
   // calling getSum function with different arguments
   getSum(3,5);
   getSum((float)3.2, (float)5.7);
   getSum(4, 7, 9);
   
   return 0;
}

Output
Inside getSum 3 5
Inside getSum 3.2 5.7
Inside getSum 4 7 9