C++ Functions, Overloading, Pass-by-Reference & Lambdas Masterclass
Welcome to Phase 6 (Chapter 6): C++ Functions, Overloading, Pass-by-Reference & Lambdas Masterclass! Functions modularize code. In Modern C++, pass-by-reference (const T&) prevents unnecessary copying, function overloading enables polymorphic signatures, and lambda expressions (C++11) provide inline anonymous functions.
| Passing Strategy | Syntax | Copy Overhead? | Can Modify Original? |
|---|---|---|---|
| Pass-by-Value | void f(int x) | Yes (Full copy made) | No (Operates on copy) |
| Pass-by-Reference | void f(int &x) | No (Zero-copy alias) | Yes (Modifies original variable) |
| Pass-by-Const-Reference | void f(const std::string &s) | No (Zero-copy alias) | No (Read-only protection!) |
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
// Function Overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
// Pass-by-Reference to swap
void swapValues(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
std::cout << "int add: " << add(10, 20) << "\n";
std::cout << "double add: " << add(5.5, 4.3) << "\n";
int x = 100, y = 200;
swapValues(x, y);
std::cout << "After swap: x=" << x << ", y=" << y << "\n";
// C++11 Lambda Expression
auto square = [](int n) { return n * n; };
std::cout << "Lambda square(6): " << square(6) << "\n";
return 0;
} Q1: When should I pass by const T& vs pass by value?
Pass primitive types (`int`, `double`, `char`) by value. Pass objects, strings, vectors, and custom structs by `const T&` to eliminate copy overhead.
Q2: How does function overloading work under the hood?
The C++ compiler uses Name Mangling to encode parameter types directly into the binary symbol name (e.g. `_Z3addii` vs `_Z3adddd`).
Q3: What are inline functions?
Functions declared `inline` hint to the compiler to substitute the function body directly at call sites to eliminate call overhead.
Q4: What is a lambda capture clause []?
`[]` captures no variables. `[=]` captures surrounding variables by value. `[&]` captures surrounding variables by reference.
Q5: Can default argument values be specified in function definitions?
Default arguments should be specified in the function declaration (prototype) in header files, NOT repeated in the definition body.