C++
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C++
-
Section 4: Memory Management
-
Section 5: Templates and Generic Programming
-
Section 6: The Standard Template Library
-
Section 7: Modern C++ Features
-
Section 8: Error Handling
-
Section 9: Multithreading
-
Section 10: Operator Overloading and Type Conversion
-
Section 11: Advanced Topics
-
Section 12: Tooling and Build Systems
-
Section 13: Design Patterns in C++
-
Section 14: Interfacing with C and Systems Programming
-
Section 15: Networking and IPC Basics
-
Section 16: Graphics and Game Programming Basics
-
Section 17: The Boost Libraries
-
Section 18: Data Structures and Algorithms in C++
-
Section 19: Practical Projects
-
Section 20: More Concurrency Patterns
-
Section 21: More OOP and Design Practice
-
Section 22: File I/O and Streams
-
Section 23: More Standard Library
-
Section 24: Practice Exercises
-
Section 25: Interview and Algorithm Practice
-
Section 26: Compiler and Language Internals
-
Section 27: GUI and Application Frameworks Overview
-
Section 28: Testing and Quality Practices
-
Section 29: Numerics Library
-
Section 30: Concepts Library (C++20)
-
Section 31: Ranges Library (C++20) In Depth
-
Section 32: More Utility Library
7: Variables, Types, and References
Why can't I just use one type for all numbers?
Coming from languages like Python or JavaScript, C++'s insistence on int, float, double, and long feels like unnecessary bookkeeping. But here's the thing: C++ is designed to give you direct control over how much memory your program consumes. Every byte counts when you're writing high-performance code.
Think of it like choosing a storage container. If you're storing the number of lives a player has in a game, an int is perfect. You'll never have 3.5 lives. But if you're calculating the trajectory of a projectile or the precise coordinates of a character in a 3D space, an int will chop off all your decimals (truncation), and your character will just teleport in jagged jumps. That's where double comes in.
int lives = 3;
double healthPercentage = 94.2;
bool isGameOver = false;
// If I try to put 94.2 into an int, C++ just throws the .2 away.
int brokenHealth = healthPercentage; // brokenHealth is now 94
I usually default to double for decimals because modern hardware handles it efficiently, and float is mostly reserved for specific cases like GPU programming or massive arrays where memory is extremely tight.
What exactly is a reference, and why not just copy the variable?
This is where a lot of learners get tripped up. A reference is essentially a "nickname" or an alias for an existing variable. When you create a reference using the & symbol, you aren't creating a new piece of data; you're just creating a new way to talk to the same spot in memory.
Imagine you have a massive object—like a 3D model of a city with thousands of coordinates. If you pass that object into a function to change its color, C++'s default behavior is to copy the entire city. That's a massive waste of CPU and RAM. By using a reference, you're telling the function, "Don't make a copy; just go to this specific address and change the original."
void applyDamage(int& currentHealth, int damage) {
currentHealth -= damage; // This modifies the actual variable passed in
}
int main() {
int playerHP = 100;
applyDamage(playerHP, 20);
// playerHP is now 80 because we passed it by reference
}
If I had removed that & from the function signature, the function would have created a local copy of playerHP, subtracted 20 from the copy, and then deleted that copy when the function ended. The original playerHP would have stayed at 100, and you'd be wondering why your enemies aren't doing any damage.
Does it actually matter if I initialize a variable immediately?
In short: yes, it matters immensely. In some languages, an uninitialized variable defaults to 0 or null. In C++, it contains "garbage data"—whatever random bits happened to be left over in that memory address by the last program that used it.
I've seen veteran devs waste hours debugging a "random" bug only to realize they declared int score; without setting it to 0, and the program started the game with the player having -1,294,832,102 points. It's a nasty habit that leads to non-deterministic bugs (bugs that only happen sometimes).
int a = 0; // Safe. Initialized.
int b; // Dangerous. Contains "garbage" value.
int c{10}; // Also safe. This is "uniform initialization" (C++11 and later).
I highly recommend using the { } syntax (uniform initialization). Not only is it consistent across all types, but it also prevents "narrowing conversions"—meaning the compiler will yell at you if you try to accidentally cram a double into an int.
📋 Practical Task
Exercise: Building a Character Stat Modifier
Your task is to create a small program that manages a character's attributes. You need to demonstrate your understanding of different types and the use of references to modify data.
- Create an
intforlevel, adoubleforexperiencePoints, and aboolforisAlive. - Write a function called
gainExperiencethat takes the experience variable by reference and adds a specific amount to it. - Write a second function called
levelUpthat takes the level variable by reference and increments it by 1. - In your
mainfunction, initialize your character, call the experience function, and then call the level-up function. - Print the final stats to the console to verify that the original variables were actually modified.
There are no comments for now.