C++ ยท Chapter 27 of 49

C++ Function Parameters

Parameters can be passed by value (a copy), by reference (`&`, the original), or by pointer. C++ also supports default parameter values and function overloading based on parameter types.

Choosing pass-by-value vs pass-by-reference matters for both performance (avoiding copies of large objects) and correctness (whether the function should modify the caller's data).

Default parameters

`void greet(std::string name = "Guest")` lets you call `greet()` without an argument, using "Guest" automatically.

Pass by value vs reference

Pass by value copies the argument โ€” changes inside the function don't affect the caller. Pass by reference (`int&`) shares the same memory, so changes do affect the caller.

Example 1 (cpp)
void greet(std::string name = "Guest") {
    std::cout << "Hello " << name;
}
int main() { greet(); }
Output
Hello Guest

The default value is used since no argument was passed.

Example 2 (cpp)
void square(int& n) { n = n * n; }
int main() {
    int x = 4;
    square(x);
    std::cout << x;
}
Output
16

Passing by reference lets square() modify x directly.

Key points

  • Default parameters provide a fallback value.
  • Pass by value copies; pass by reference shares memory.
  • Use const T& to pass efficiently without allowing mutation.
  • Default parameters must come after non-default ones.
๐Ÿ’ก Note: Always mark reference parameters as `const` if the function shouldn't modify them, to signal intent and prevent bugs.

๐Ÿ“ Quick Quiz

1. What lets a parameter be omitted when calling a function?

2. Pass by value means:

3. Which is used for efficient, read-only passing of large objects?