Lesson 10 of 45
C++Lesson 10: Function Overloading
8 min
Course progress22%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 10 of 45
C++8 min
Keep these ideas in mind as you work through the lesson.
C++ allows multiple functions with the same name but different signatures (parameter types, number, or const‑qualifiers). Overload resolution picks the best match based on the arguments supplied. Ambiguities arise when two overloads are equally viable.
void print(int i) {
std::cout << \"Integer: \" << i << '\
';
}
void print(double d) {
std::cout << \"Double: \" << d << '\
';
}
void print(const std::string& s) {
std::cout << \"String: \" << s << '\
';
}
int main() {
print(42); // calls int overload
print(3.14); // calls double overload
print(std::string(\"hi\")); // calls string overload
return 0;
}
Pitfall: If you add void print(long l); and call print(42);, the compiler may be ambiguous because both int and long are viable.
Tip: Use the
explicitkeyword on single‑argument constructors to avoid unintended implicit conversions.
<Alert type="warning">You cannot overload on return type alone; the return type is not considered in overload resolution.