3. C++ Functions, Default Arguments & Overloading

Comprehensive Guide: Pass-by-reference, default parameters, compile-time function overloading & recursion

Module 1: Pass by Value vs Pass by Reference

Modifying caller variables directly vs copying argument values.

🇬🇧 English Definition

Pass by Reference passes variable references directly into function parameters, enabling functions to modify caller variables without return statements.

🇮🇳 Hinglish Definition

Pass by Reference me function parameter ke aage & lagane par original variable pass hota hai jisse changes directly apply hote hai.

Core Concepts & Rules

  • Pass by Value: void swap(int a, int b) -> Copies values (Original unchanged).
  • Pass by Reference: void swap(int &a, int &b) -> Modifies originals!

🔍 Line-by-Line Code Breakdown

  1. Line 1-5: swapValues function accepting int &x, int &y references to swap values.
  2. Line 8-10: Call swapValues(a, b) in main().
💻 Practical C++ Code Example - Pass by Value vs Pass by Reference
using namespace std;

void swapValues(int &x, int &y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 10, b = 20;
    swapValues(a, b);
    cout << "Swapped Values: a = " << a << ", b = " << b << endl;
    return 0;
}
📤 Compiled C++ Output:
Swapped Values: a = 20, b = 10

Module 2: Function Overloading (Compile-Time Polymorphism)

Defining multiple functions with identical names but distinct parameter lists.

🇬🇧 English Definition

Function Overloading is a feature that allows a class or program to have multiple functions with the same name if their parameter types or counts differ.

🇮🇳 Hinglish Definition

Function Overloading me ek hi naam ke multiple functions hote hai lekin unke arguments alag hote hai.

Core Concepts & Rules

  • Differentiated by parameter count, data types, or parameter order.
  • Return type alone CANNOT overload functions.

🔍 Line-by-Line Code Breakdown

  1. Line 1: Overload 1: int add(int a, int b) adds integers.
  2. Line 2: Overload 2: double add(double a, double b) adds floating values.
  3. Line 5-6: Compiler selects correct overload based on argument types.
💻 Practical C++ Code Example - Function Overloading (Compile-Time Polymorphism)
using namespace std;

int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }

int main() {
    cout << "Integer Addition: " << add(5, 10) << endl;
    cout << "Double Addition:  " << add(4.5, 3.2) << endl;
    return 0;
}
📤 Compiled C++ Output:
Integer Addition: 15 Double Addition: 7.7