C++ Function Overloading
Function overloading in C++ allows you to create multiple functions with the same name but different parameter lists. The compiler determines which function to call based on the number or types of arguments passed. This helps improve code readability and allows using the same function name for similar tasks.
Rules for Function Overloading
- Functions must have the same name.
- Parameter lists must differ by number of parameters or type of parameters.
- Return type alone cannot be used to distinguish overloaded functions.
Example Program
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Function to add two doubles
double add(double a, double b) {
return a + b;
}
int main() {
int sumInt = add(10, 20);
double sumDouble = add(5.5, 2.3);
cout << "Sum of integers: " << sumInt << endl;
cout << "Sum of doubles: " << sumDouble << endl;
return 0;
}
Output
Sum of integers: 30 Sum of doubles: 7.8
Important Notes
- Function overloading increases code readability by allowing similar operations to share the same function name.
- The compiler selects the correct function based on the arguments used in the function call.
- Overloaded functions can have different parameter types, different numbers of parameters, or both.
Next Topic
Next, learn about Inline Functions in C++.