C++ Overloading
Function overloading is the use of one name for several functions. Each version takes different parameters, so the compiler can pick one for a call.
One name, two types
Both functions are named add. One takes two ints and the other takes two doubles.
#include <iostream>
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
std::cout << add(2, 3) << std::endl;
std::cout << add(2.0, 3.5) << std::endl;
return 0;
}One name, two counts
The first show function takes one value and prints it. The second show function takes two values and prints their sum.
#include <iostream>
void show(int a) {
std::cout << a << std::endl;
}
void show(int a, int b) {
std::cout << a + b << std::endl;
}
int main() {
show(7);
show(4, 5);
return 0;
}Example
#include <iostream>
#include <string>
void show(int value) {
std::cout << "Number: " << value << std::endl;
}
void show(std::string text) {
std::cout << "Text: " << text << std::endl;
}
int main() {
std::string word = "Hello";
show(42);
show(word);
return 0;
}Key points
- Overloaded functions use the same name.
- Each version takes parameters of different types, or a different number of parameters.
- The compiler picks the version that matches the arguments in a call.
- Two int arguments pick the int version of a function.
- Two double arguments pick the double version of a function.
In this example, one show function takes an int and prints it beside a label. The other show function takes a string and prints it beside a label. Each call picks the version that matches its argument.
Note
Two versions with matching parameters clash, even under one shared name.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does the compiler pick between two functions that share a name?