capypad
0 day streak
cpp / beginner
Snippet

Function Overloading: Same Name, Different Parameters

Function overloading allows multiple functions with the same name if they have different parameter types or counts. The compiler determines which version to call based on the argument types. This improves code readability.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
 
int add(int a, int b) {
return a + b;
}
 
double add(double a, double b) {
return a + b;
}
 
int main() {
cout << add(5, 3) << endl;
cout << add(2.5, 1.3) << endl;
return 0;
}
Breakdown
1
int add(int a, int b)
Version for integer parameters
2
double add(double a, double b)
Version for double parameters, same function name
3
cout << add(5, 3)
Calls integer version
4
cout << add(2.5, 1.3)
Calls double version