Functions: Default Arguments, Inline, Pass by Reference
C++ references give you the power of pointers without the confusing `*` and `&` dereferencing syntax.
What is it?
A reference (`&`) is an alias (alternative name) for an existing variable. Pass-by-reference allows functions to directly access and modify caller variables without copying.
Why is it used?
Passing large objects (strings, vectors, structs) by value copies thousands of bytes. Passing by `const &` passes an alias with zero copy overhead.
Detailed Explanation
Function Enhancements in C++:
• Pass by Reference (`int &x`): Modifies caller variable directly without pointer dereferencing.
• Pass by Const Reference (`const std::string &str`): Zero-copy performance + safety.
• Default Arguments: `void print(int x = 10);` (must be defined from right to left).
• Inline Functions (`inline`): Suggests the compiler replace the function call directly with its code body to eliminate call overhead for small functions.
Syntax Structure
Syntax Blueprint
void calculate(int a, int &result); // Pass by reference
void printText(const std::string &text); // Pass by const reference
Code Example
CPP Code
#include <iostream>
#include <string>
// 1. Pass by Reference: Swaps variables without pointers!
void swap_numbers(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
// 2. Pass by Const Reference with Default Argument
void display_course_badge(const std::string &title, int discount_pct = 0) {
std::cout << "Course: " << title;
if (discount_pct > 0) {
std::cout << " [Special " << discount_pct << "% Discount!]";
}
std::cout << "\n";
}
int main() {
int x = 100, y = 200;
std::cout << "Before swap: x=" << x << ", y=" << y << "\n";
swap_numbers(x, y); // Clean call without & or *!
std::cout << "After swap: x=" << x << ", y=" << y << "\n\n";
display_course_badge("KLiC Advanced Python"); // Uses default 0%
display_course_badge("Data Analytics Pack", 28);
return 0;
}
Explanation of the Code
• `swap_numbers(int &a, int &b)` accepts references. Caller simply passes `x, y` without taking addresses.
• `const std::string &title` avoids copying string characters in memory.
Expected Output
Before swap: x=100, y=200
After swap: x=200, y=100
Course: KLiC Advanced Python
Course: Data Analytics Pack [Special 28% Discount!]
Real-World Application
Virtually every C++ function taking strings, vectors, or objects uses `const T&` for performance.
Common Mistakes to Avoid
• Returning a reference to a local stack variable (leads to dangling references and undefined behavior).
• Defining default arguments in both the declaration and definition (define them only in the declaration/header!).
Quick Practice Challenge
Write a function `increment(int &val)` that increments the passed integer in place.
Key Takeaways
• References (`&`) act as clean aliases to existing variables.
• Always pass complex objects by `const Type&` to avoid copies.
• Default arguments must appear at the end of the parameter list.