C++ Functions, Overloading, Pass-by-Reference & Lambdas Masterclass

โšก Modern C++ (C++17 / C++20 / C++23) ๐ŸŸข Lesson 6 ๐Ÿ“‚ Phase 06: Functions & Modular Code ๐Ÿ“… 2026 Master Edition
๐Ÿ“Œ Covered in this in-depth guide: Function Prototypes ยท Pass-by-Value vs Pass-by-Reference ยท const T& Performance Rule ยท Function Overloading ยท inline Functions ยท C++11 Lambdas

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.

1Pass-by-Value vs Pass-by-Reference (const T&)
Passing StrategySyntaxCopy Overhead?Can Modify Original?
Pass-by-Valuevoid f(int x)Yes (Full copy made)No (Operates on copy)
Pass-by-Referencevoid f(int &x)No (Zero-copy alias)Yes (Modifies original variable)
Pass-by-Const-Referencevoid f(const std::string &s)No (Zero-copy alias)No (Read-only protection!)
2Function Overloading & Modern Lambdas
C++ โ€” Overloading, References & Lambdasโ–ถ Run Code in C++ Compiler
#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;
}
3Technical FAQs

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.