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?
| Feature | What It Does | Example |
|---|---|---|
| Function Overloading | Same function name, different parameter types/counts | int add(int, int) and double add(double, double) |
| Default Parameters | Arguments with fallback values if not provided | void greet(string name = "World") |
| Pass-by-Reference | Function modifies the caller's original variable | void doubleIt(int& x) |
| Const Reference | Avoids copying without allowing modification | void print(const string& s) |
| Static Local | Variable that persists between function calls | static 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.