What is function overloading in C++?

With function overloading, we can create multiple functions with the same name. This may be achieved with one of the below cases:

  • Different number of arguments
  • Different types of arguments

Different number of arguments

A function can be overloaded by having a different number of arguments for each function with the same name.

// same name diffenrent number of arguments 
int add(int a, int b);
int add(int a, int b, int c);

In the code above, we created two functions with the same name, but each function has a different number of arguments.

#include <iostream>
using namespace std;
int add(int a, int b){
return a + b;
}
int add(int a, int b, int c){
return a + b + c;
}
int main() {
cout << "calling add with three arguments: " << add(10, 20, 30) << endl;
cout << "calling add with two arguments: " << add(10, 20) << endl;
return 0;
}
Function overloading with a different number of arguments

Different types of arguments

A function can be overloaded by having different types of arguments for each function with the same name.

// same name diffenrent argument types
int absolute(int a);
int absolute(float a);

In the code above, we created two functions with the same name, but each function has a different type of argument.

#include <iostream>
using namespace std;
int absolute(int a){
return a < 0 ? -a : a;
}
int absolute(float a){
return a < 0.0 ? -a : a;
}
int main() {
cout << "calling absolute with float value : " << absolute(-1.3f) << endl;
cout << "calling absolute with int value: " << absolute(-10) << endl;
return 0;
}
Function overloading with different types of arguments

The overloaded function can have different return types.

Invalid function overloading

Only changing return type

We cannot achieve function overloading by only changing the return type.

// this will throw compile time error 
int test();
float test();

The above code will throw a compile-time error because the compiler gets ambiguity on which test method should be called.


Default value in function

// ambiguity error 
int add(int a)
int add(int a, int b = 10);

add(4);

In the code above, we have added the default value for the second add function. By compiling the compiler, we will get ambiguity on which add method should be executed upon calling add with a single argument.

Free Resources