• Home
  • What is Function Overloading in C++?

What is Function Overloading in C++?

Function overloading in C++ is the ability to create multiple functions with the same name but with different parameters. This allows you to create multiple versions of a function that can each perform a different task, depending on the parameters that are passed to it.

For example, you might create an “add” function that can be used to add two numbers, three numbers, or four numbers, depending on the number of parameters that are passed to it. This can be useful for creating more flexible and reusable code, as you can use the same function name for multiple purposes without having to create separate functions for each task.

To use function overloading in C++, you simply need to define multiple functions with the same name but with different parameter lists. When you call the function, the compiler will automatically choose the correct version of the function based on the number and type of the parameters that you pass to it.

Here’s an example of how you might use function overloading in C++:

#include <iostream>

// Define an "add" function that takes two integers as parameters
int add(int a, int b) {
return a + b;
}

// Define another "add" function that takes three integers as parameters
int add(int a, int b, int c) {
return a + b + c;
}

// Define yet another "add" function that takes four integers as parameters
int add(int a, int b, int c, int d) {
return a + b + c + d;
}

int main() {
// Call the "add" function with two parameters
int result1 = add(1, 2);
std::cout << "Result 1: " << result1 << std::endl;

// Call the "add" function with three parameters
int result2 = add(1, 2, 3);
std::cout << "Result 2: " << result2 << std::endl;

// Call the "add" function with four parameters
int result3 = add(1, 2, 3, 4);
std::cout << "Result 3: " << result3 << std::endl;
}

In this example, we have defined three versions of the “add” function, each with a different number of parameters. When we call the “add” function with two parameters, the compiler will choose the first version of the function (which takes two integers as parameters). When we call the “add” function with three parameters, the compiler will choose the second version of the function (which takes three integers as parameters), and so on.