C++ Function Overloading
Function overloading in C++ allows multiple functions to have the same name with different parameter lists. The compiler distinguishes them based on the number and type of parameters.
1. Function Overloading Syntax
You can define multiple functions with the same name but different parameter types or counts.
C++
Syntax of function overloading
return_type function_name(type1 param1);
return_type function_name(type1 param1, type2 param2);
return_type function_name(type2 param1, type3 param2);
2. Function Overloading Example
This example demonstrates function overloading with different parameter types and counts.
C++
Example: Function overloading
#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() {
cout << add(2, 3) << endl; // Calls first function
cout << add(2, 3, 4) << endl; // Calls second function
cout << add(2.5, 3.5) << endl; // Calls third function
return 0;
}
3. Common Mistakes
Function overloading cannot differ only by return type. Parameter lists must differ by number or type. Overloading with default arguments can also cause ambiguity.
Conclusion
C++ function overloading allows multiple functions with the same name but different parameters. It improves code readability and flexibility by reusing function names for similar tasks.
Codecrown