Dashboard/Block 1: Foundation/Module 4
Module 4Foundation

Functions in C++ (Deep Dive)

Alright, so you already know how to write a basic function in C, right? You pick a return type, give it a name, throw in some parameters, and write the body. Cool. But what if I told you that C++ lets you do some seriously powerful things with functions that C just... can't? That's what this week is all about — leveling up your function game.

Let's start with something that probably annoyed you in C. Say you want an add function for integers, and another one for doubles. In C, you'd have to name them differently — addInt(), addDouble(), whatever. Ugly, right? Well, C++ says "nah, just call them both add" — and the compiler figures out which one you meant based on what you pass in. That's called function overloading, and it's our first big topic.

Then we've got default parameters and pass-by-reference. Default parameters are like fallback values — think of it like this: if someone doesn't tell you their name, you just say "Hello, World!" instead. And pass-by-reference (that little & symbol) lets your function reach out and actually change the original variable, instead of just playing with a copy. We'll also dig into scope and lifetime — basically, where can your variable be seen, and how long does it stick around in memory?

FeatureWhat It DoesExample
Function OverloadingSame function name, different parameter types/countsint add(int, int) and double add(double, double)
Default ParametersArguments with fallback values if not providedvoid greet(string name = "World")
Pass-by-ReferenceFunction modifies the caller's original variablevoid doubleIt(int& x)
Const ReferenceAvoids copying without allowing modificationvoid print(const string& s)
Static LocalVariable that persists between function callsstatic int count = 0;

By the end of this week, you'll be writing functions that are cleaner, more flexible, and way more efficient than anything you could pull off in plain C. Let's get into it.

Learning Objectives

Use function overloading (same name, different parameters)
Set default parameter values
Pass arguments by reference with &
Use const references for read-only access without copying
Understand variable scope and lifetime

Key Concepts

Function Overloading

Default Parameters & References

Scope & Lifetime