Function Overloading is a feature of C++ where two or more functions can share the exact same name, provided their parameter lists (number, types, or order of arguments) are distinctly different. This is a primary form of Compile-Time (Static) Polymorphism.
#include <iostream>
#include <string>
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
std::string add(const std::string& a, const std::string& b) {
return a + b;
}
int main() {
std::cout << "Integers: " << add(10, 20) << "\n"; // Calls add(int, int) -> 30
std::cout << "Doubles: " << add(4.5, 2.5) << "\n"; // Calls add(double, double) -> 7.0
std::cout << "Strings: " << add("Hello ", "Veewom") << "\n"; // Calls add(string, string) -> Hello Veewom
return 0;
}
Beware of default arguments and type promotions! If you define void print(int x) and void print(float x), calling print(5.5) causes ambiguity because 5.5 is a double literal, which can convert equally to int or float. Write print(5.5f) to be explicit.
Boost your C++ proficiency by studying these closely connected core modules:
Fundamentals of parameter passing.
Generic functions vs overloaded functions.
Comparing compile-time vs runtime polymorphism.