Unlike C, where every function needs a distinct name, C++ allows multiple functions to share a name as long as their parameter lists differ — the compiler selects the correct overload based on the actual argument types at each call site, resolved entirely at compile time. Default arguments let trailing parameters be omitted by the caller, falling back to a specified default. And where C requires an explicit pointer to let a function modify a caller's variable, C++ offers reference parameters (&) as a cleaner alternative — the syntax at the call site looks identical to passing by value, while the function still operates on the original.
Function overloading: a genuine C++ addition
C would require three separately-named functions (addInt, addDouble, addThree) for this same idea — C++ lets all three share the name add, with the compiler choosing the right one based on the actual arguments at each call site.
int add(int a, int b) {
return a + b;
}
double add(double a, double b) { // overload: different parameter types
return a + b;
}
int add(int a, int b, int c) { // overload: different parameter count
return a + b + c;
}
add(1, 2); // calls the (int, int) version
add(1.5, 2.5); // calls the (double, double) versionDefault arguments
Callers can omit trailing arguments and get the specified default — note that once a parameter has a default, every parameter after it must also have one.
void greet(std::string name, std::string greeting = "Hello") {
std::cout << greeting << ", " << name << "!\n";
}
greet("Alice"); // "Hello, Alice!" — greeting uses its default
greet("Bob", "Hi there"); // "Hi there, Bob!" — explicit overrideReference parameters: cleaner than C's pointers
The call site looks exactly like passing by value — no & needed when calling — but the function genuinely modifies the caller's original variable, since a reference parameter is an alias for the original, not a separate copy.
void doubleIt(int &n) { // & means n is a REFERENCE, an alias for the caller's variable
n = n * 2;
}
int x = 5;
doubleIt(x); // no & needed at the call site
std::cout << x << "\n"; // 10 — x WAS modified, through the reference