capypad
0 day streak
cpp / beginner
Snippet

Function Overloading: Multiple Functions with Same Name

Function overloading allows multiple functions with the same name but different parameter types. The compiler determines which function to call based on the argument types. This improves code readability by using descriptive names for similar operations. Each overloaded function must have a unique parameter signature.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
 
int add(int a, int b) {
std::cout << "Using int version" << std::endl;
return a + b;
}
 
double add(double a, double b) {
std::cout << "Using double version" << std::endl;
return a + b;
}
 
std::string add(std::string a, std::string b) {
std::cout << "Using string version" << std::endl;
return a + b;
}
 
int main() {
std::cout << add(5, 3) << std::endl;
std::cout << add(2.5, 3.7) << std::endl;
std::cout << add(std::string("Hello "), std::string("World")) << std::endl;
return 0;
}
Breakdown
1
int add(int a, int b)
Integer version of add function
2
double add(double a, double b)
Different parameter types create an overload
3
std::string add(std::string a, std::string b)
String version allows concatenation with + operator