Function Overloading in C++

Introduction

  • C++ provides new feature that is function overloading. It can be considered as an example of polymorphism feature in C++.
  • If two or more functions have same name but different parameters, it is said to be Function Overloading.
  • It allows you to use the same function name for different functions in the same scope/class.
  • It is used to enhance the readability of the program.
There are two ways to overload a function:
1. Different number of arguments.
2. Different datatypes of argument.

1. Different number of arguments

In different number of arguments, two functions have same name but different number of parameters/arguments of the same datatype.

Example: Demonstrating function overloading with different number of arguments

#include<iostream>
using namespace std;
int add(int a, int b)
{
     cout<<a+b<<endl;
}
int add(int a, int b, int c)
{
     cout<<a+b+c<<endl;
}
int main()
{
     add(10,20);
     add(10,20,30);
}


Output:
30
60

In the above example, the add() function is overloaded with two and three arguments.

2. Different datatypes of argument

In different datatypes of argument, you can define two or more functions with same name and same number of parameters but with the different datatype of parameters/arguments.

Example : Demonstrating Function Overloading with different datatypes of argument

#include<iostream>
using namespace std;
int add(int a, int b)
{
     cout<<a+b<<endl;
}
double add(double a, double b)
{
     cout<<a+b<<endl;
}
int main()
{
     add(10,20);
     add(10.5,20.5);
}


Output:
30
31