C++ - Function Overloading

Function overloading in C++ allows you to define multiple functions with the same name but different parameter lists. These functions can perform similar operations but on different types of data or with different numbers of parameters. The compiler determines the appropriate function to call based on the arguments provided.

  • Function Name: All overloaded functions must have the same name.
  • Parameter List: Overloaded functions must have different parameter lists, either in terms of the number of parameters or the types of parameters. The order of parameters does not matter.
  • Return Type: The return type of the overloaded functions does not play a role in determining which function to call. Only the function name and parameter list are considered.
  • Function Signature: The function signature includes the function name and the parameter list. Two functions with the same name but different parameter lists have different function signatures.
  • Function Overload Resolution: The compiler determines which overloaded function to call based on the arguments provided. It looks for the best match by considering the exact match of types, promotions, and standard conversions. If no exact match is found, the compiler attempts to perform implicit conversions to find a compatible match. If there are multiple viable matches, an ambiguous function call error occurs.
#include <iostream>
// Function to add two integers
int add(int a, int b) {
    return a + b;
}
// Function to add two floating-point numbers
float add(float a, float b) {
    return a + b;
}
// Function to concatenate two strings
std::string add(const std::string& str1, const std::string& str2) {
    return str1 + str2;
}
int main() {
    int result1 = add(3, 5);
    std::cout << "Result 1: " << result1 << std::endl;  // Output: 8
    float result2 = add(2.5f, 3.7f);
    std::cout << "Result 2: " << result2 << std::endl;  // Output: 6.2
    std::string result3 = add("Hello, ", "World!");
    std::cout << "Result 3: " << result3 << std::endl;  // Output: Hello, World!
    return 0;
}

In this example, three functions named add are defined with different parameter lists. The first add function takes two integers and returns their sum. The second add function takes two floating-point numbers and returns their sum. The third add function takes two std::string objects, concatenates them, and returns the result.

In the main function, the appropriate add function is called based on the provided arguments. The compiler selects the correct function based on the argument types.