1 Answers
In C++, two functions can have the same name if the number and/or type of arguments passed are different. These functions have the same name but other 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.
/ Program to compute absolute value // Works for both int and float #include <iostream> using namespace std; // function with float type parameter float absolute(float var){ if (var < 0.0) var = -var; return var; } // function with int type parameter int absolute(int var) { if (var < 0) var = -var; return var; } int main() { // call function with int type parameter cout << "Absolute value of -5 = " << absolute(-5) << endl; // call function with float type parameter cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl; return 0; }
Read this for more details: https://www.programiz.com/cpp-programming/function-overloading