capypad
0 day streak
cpp / beginner
Snippet

Function Overloading

Function overloading allows multiple functions with the same name but different parameter types. The compiler determines which function to call based on the arguments passed. This makes code more readable by using descriptive names for similar operations on different data types.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
 
int add(int a, int b) {
return a + b;
}
 
double add(double a, double b) {
return a + b;
}
 
std::string add(std::string a, std::string b) {
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)
First overload for integer parameters
2
double add(double a, double b)
Second overload for floating-point parameters
3
std::string add(std::string a, std::string b)
Third overload for string parameters
4
std::cout << add(5, 3) << std::endl;
Compiler automatically chooses the int version