cpp / beginner
Snippet
Function Overloading: Multiple Functions 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 provides a clean way to define operations that work similarly across different data types.
snippet.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;}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 addition
2
double add(double a, double b)
Second overload for floating-point addition
3
std::string add(...)
Third overload for string concatenation
4
add(5, 3)
Compiler selects int version based on integer arguments