In C++, two functions can have the same name if the number and/or type of arguments passed is different.
These functions having the same name but different arguments are known as overloaded functions. For example:
// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Here, all 4 functions are overloaded functions.
Notice that the return types of all these 4 functions are not the same. Overloaded functions may or may not have different return types but they must have different arguments. For example,
// Error code
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, the same type, and the same number of arguments. Hence, the compiler will throw an error.
Example 1: Overloading Using Different Types of Parameter
Output
Absolute value of -5 = 5 Absolute value of 5.5 = 5.5
In this program, we overload the absolute() function. Based on the type of parameter passed during the function call, the corresponding function is called.
Example 2: Overloading Using Different Number of Parameters
Output
Integer number: 5 Float number: 5.5 Integer number: 5 and double number: 5.5
Here, the display() function is called three times with different arguments. Depending on the number and type of arguments passed, the corresponding display() function is called.
The return type of all these functions is the same but that need not be the case for function overloading.
Note: In C++, many standard library functions are overloaded. For example, the sqrt() function can take double, float, int, etc. as parameters. This is possible because the sqrt() function is overloaded in C++.