Function overloading in C++ allows you to define multiple functions with the same name but with different parameter lists (different number or types of parameters). The compiler determines which version of the function to call based on the arguments passed to it.
Main Points
1. Same Function Name: All overloaded functions have the same name.
2. Different Parameters: They must have different parameter types or a different number of parameters.
3. The return type is not considered when overloading functions, so it doesn’t help in distinguishing overloaded functions.
Example:
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Function to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Function to add two doubles
double add(double a, double b) {
return a + b;
}
int main() {
int sum1 = add(10, 15); // Calls the version with two int parameters
int sum2 = add(10, 15, 20); // Calls the version with three int parameters
double sum3 = add(7.5, 8.5); // Calls the version with two double parameters
cout << "Sum of two numbers 10 and 15: " << sum1 << endl;
cout << "Sum of three numbers 10, 15, and 20: " << sum2 << endl;
cout << "Sum of two double numbers 7.5 and 8.5: " << sum3 << endl;
return 0;
}
Output:
Sum of two numbers 10 and 15: 25
Sum of three numbers 10, 15, and 20: 45
Sum of two double numbers 7.5 and 8.5: 16
Sum of three numbers 10, 15, and 20: 45
Sum of two double numbers 7.5 and 8.5: 16
Explanation:
- First add() function: Takes two integers and returns their sum.
- Second add() function: Takes three integers and returns their sum.
- Third add() function: Takes two doubles and returns their sum.