Function Overloading in C++
Function overloading allows multiple functions with the same name to exist but with different parameter types or counts. This makes functions more flexible and adaptable to various inputs.
Example: Overloading Functions to Add Integers and Doubles
#include <iostream>
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded function to add two doubles
double add(double a, double b) {
return a + b;
}
int main() {
int intResult = add(10, 20);
double doubleResult = add(5.5, 7.3);
std::cout << "Integer addition result: " << intResult << std::endl;
std::cout << "Double addition result: " << doubleResult << std::endl;
return 0;
}
Output:
Integer addition result: 30
Double addition result: 12.8
Explanation: Here, we define two add
functions with different parameter types. The first add
function accepts two integers, and the second one accepts two doubles. The appropriate function is called based on the argument types passed to it.
Key Takeaways
- Function overloading allows functions with the same name but different parameters to coexist.
- Overloading increases flexibility, allowing the same function name to handle various data types.
- The compiler decides which function to call based on the argument types passed.