capypad
0 day streak
cpp / beginner
Snippet

Function Overloading Basics

Function overloading allows multiple functions with the same name but different parameters. The compiler distinguishes them by the number, type, or order of parameters. When you call add, the compiler picks the version that matches your arguments. This makes code more readable since related operations share the same conceptual name.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
int add(int a, int b) {
return a + b;
}
 
double add(double a, double b) {
return a + b;
}
 
int add(int a, int b, int c) {
return a + b + c;
}
 
int main() {
std::cout << "int + int: " << add(3, 5) << std::endl;
std::cout << "double + double: " << add(2.5, 3.7) << std::endl;
std::cout << "three ints: " << add(1, 2, 3) << std::endl;
return 0;
}
Breakdown
1
int add(int a, int b) {
First overload: accepts two integers
2
return a + b;
Returns sum of two integers
3
}
Closes the first add function
4
double add(double a, double b) {
Second overload: accepts two doubles
5
return a + b;
Returns sum of two doubles
6
}
Closes the second add function
7
int add(int a, int b, int c) {
Third overload: accepts three integers
8
return a + b + c;
Returns sum of three integers
9
}
Closes the third add function
10
std::cout << "int + int: " << add(3, 5) << std::endl;
Calls two-argument int version, prints 8
11
std::cout << "double + double: " << add(2.5, 3.7) << std::endl;
Calls two-argument double version, prints 6.2
12
std::cout << "three ints: " << add(1, 2, 3) << std::endl;
Calls three-argument int version, prints 6