Legacy C++ › 1. Getting Started
Functions
Parameters, return values, overloading, default arguments and inline functions.
beginner #functions#overloading#default-arguments#inline#pass-by-reference
Explanation
A function has a return type, a name, a parameter list and a body. C++ adds several features over C:
- Overloading: several functions with the same name but different parameter types or counts. The return type alone does not distinguish them.
- Default arguments: trailing parameters can have defaults, specified in the declaration.
- Pass by value / reference / pointer: by value copies the argument;
T&andT*let the function modify the caller’s object;const T&avoids a copy without allowing changes. inline: a hint (and an ODR relaxation) allowing the definition in a header.
Example
#include <iostream>
#include <string>
// overloads
int square(int x) { return x * x; }
double square(double x) { return x * x; }
// default argument (declared once, usually in the header)
std::string repeat(const std::string& s, int times = 2) {
std::string out;
for (int i = 0; i < times; ++i) out += s;
return out;
}
// pass by reference to modify, by const reference to read cheaply
void addExclaim(std::string& s) { s += "!"; }
std::size_t length(const std::string& s) { return s.size(); }
inline int maxOf(int a, int b) { return a > b ? a : b; }
int main() {
std::cout << square(3) << " " << square(2.5) << "\n"; // 9 6.25
std::cout << repeat("ab") << " " << repeat("ab", 3) << "\n";
std::string s = "hi";
addExclaim(s);
std::cout << s << " (" << length(s) << ")\n";
std::cout << maxOf(3, 9) << "\n";
return 0;
}
Common pitfalls
- Ambiguous overloads:
square(3L)withintanddoubleoverloads fails to choose uniquely. - Default arguments cannot be repeated in the definition if already in the declaration.
- Returning a reference or pointer to a local variable is a dangling reference.
- Passing large objects by value is slow; use
const T&. - Recursion without a base case overflows the stack.
Legacy vs modern
C++11 adds = delete / = default, constexpr functions and trailing return types; C++14 adds auto return type deduction.
Exercises
1. Why can't you overload on return type alone?
The compiler selects an overload from the call’s arguments, and f(1); may be used without looking at the result, so the return type cannot take part in the choice.
2. Write void swapInts(int& a, int& b).
void swapInts(int& a, int& b) { int t = a; a = b; b = t; }