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
- Line 1-5: swapValues function accepting int &x, int &y references to swap values.
- Line 8-10: Call swapValues(a, b) in main().
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;
}
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
- Line 1: Overload 1: int add(int a, int b) adds integers.
- Line 2: Overload 2: double add(double a, double b) adds floating values.
- Line 5-6: Compiler selects correct overload based on argument types.
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;
}