Cpp Function Overloading

In C++, function overloading is a feature that allows you to define multiple functions with the same name in the same scope, but with different parameters. These functions can have the same name but different parameter lists, and the C++ compiler will determine which function to call based on the arguments provided when the function is called. Function overloading is a form of polymorphism, which allows you to use the same function name to perform different tasks depending on the input parameters.

Here's an example in C++ to illustrate function overloading:

        
#include <iostream>

// Function with one integer parameter
int add(int a) {
    return a + 10;
}

// Function with two integer parameters
int add(int a, int b) {
    return a + b;
}

// Function with two double parameters
double add(double a, double b) {
    return a + b;
}

int main() {
    int result1 = add(5);            // Calls the first add function
    int result2 = add(3, 7);         // Calls the second add function
    double result3 = add(2.5, 3.5);  // Calls the third add function

    std::cout << "Result 1: " << result1 << std::endl;
    std::cout << "Result 2: " << result2 << std::endl;
    std::cout << "Result 3: " << result3 << std::endl;

    return 0;
}
        
    

In this example, we have three functions named add, but each of them has a different parameter list. The first add function takes an integer as its parameter, the second add function takes two integers, and the third add function takes two double-precision floating-point numbers. When you call the add function in the main function with different arguments, the C++ compiler selects the appropriate function to execute based on the number and type of arguments.

Function overloading makes code more readable and helps simplify the naming of functions. Instead of having different names for functions that perform similar operations with different types of parameters, you can use the same name, provided the parameters are different in type or number.

In this example, you can see how function overloading allows you to create functions with the same name but different behaviors based on the arguments passed to them.