Classes Introduction
Discover the power of classes in C++ to bundle data and behavior together, the cornerstone of object-oriented programming
Learn how to create classes that bundle data and behavior together, the foundation of object-oriented programming in C++.
A Simple Example
#include <iostream>
#include <string>
class Player {
public:
std::string name;
int health;
int maxHealth;
void takeDamage(int damage) {
health -= damage;
if (health < 0) {
health = 0;
}
std::cout << name << " took " << damage << " damage. Health: " << health << "/" << maxHealth << "\n";
}
void heal(int amount) {
health += amount;
if (health > maxHealth) {
health = maxHealth;
}
std::cout << name << " healed " << amount << ". Health: " << health << "/" << maxHealth << "\n";
}
bool isAlive() {
return health > 0;
}
};
int main() {
Player hero;
hero.name = "Aria";
hero.health = 100;
hero.maxHealth = 100;
hero.takeDamage(30);
hero.heal(15);
hero.takeDamage(80);
if (hero.isAlive()) {
std::cout << hero.name << " is still fighting!" << "\n";
} else {
std::cout << hero.name << " has been defeated." << "\n";
}
return 0;
}
Breaking It Down
Class Definition
- What it does: Defines a blueprint for objects combining data and functions
-
Syntax:
class ClassName { ... };- note the semicolon at the end - Members: Can contain variables (data members) and functions (member functions/methods)
- Remember: The class is the blueprint, objects are instances of that blueprint
public: Access Specifier
- What it does: Makes members accessible from outside the class
- Default: Class members are private by default (unlike structs which default to public)
- Use for: Data and methods you want users of the class to access directly
-
Remember: Put
public:before members you want to expose
Member Functions (Methods)
- What they do: Functions defined inside a class that operate on class data
- Access: Can directly access all member variables without passing them as parameters
-
Syntax: Called using dot notation:
hero.takeDamage(30); - Remember: Methods define what an object can DO
Creating Objects
- What it does: Creates an instance of the class (an actual object)
-
Syntax:
Player hero;creates a Player object named hero -
Access: Use dot notation to access members:
hero.name,hero.heal(10) - Remember: Each object has its own copy of the data members
Why This Matters
- Classes are the foundation of modern C++ and most professional software. They let you create self-contained entities that know how to manage their own data and behavior.
- Think of a BankAccount class that not only stores a balance but also knows how to deposit, withdraw, and validate transactions. This is how real-world applications are built.
Critical Insight
The magic of classes is encapsulation - bundling data with the code that operates on it. Instead of scattered functions like healPlayer(&player, 20), you have player.heal(20). The object knows how to heal itself!
This makes code more intuitive (objects are nouns, methods are verbs) and prevents mistakes - the heal method ensures health doesn't exceed maxHealth automatically.
Best Practices
Use meaningful class names: Choose names that represent real-world entities (Player, BankAccount, Invoice) in PascalCase.
Keep data members private: Expose them through public methods (getters/setters) for better control and validation. This will be covered in future lessons.
Group related functionality: A class should represent one cohesive concept. Don't mix unrelated data and behaviors.
Remember the semicolon: Class definitions must end with a semicolon after the closing brace.
Common Mistakes
Forgetting the semicolon: Class definitions end with }; not just }. This causes confusing compiler errors.
Default private access: Unlike structs, class members are private by default. You must explicitly use public: to expose them.
Not defining methods: Declaring a method in the class but never defining it causes linker errors at build time.
Accessing uninitialized members: Object members contain garbage values until initialized. Always set initial values.
Debug Challenge
This class definition is missing something important. Click the highlighted line to fix it:
Quick Quiz
- What is the main difference between a struct and a class in C++?
- How do methods access member variables?
- What does encapsulation mean?
Step Through the Code
Walk through the code step by step. Watch how variables change and see the program output at each line.
Variables
Output
Stack / Heap
Output:
Error:
Lesson Progress
- Fix This Code
- Quick Quiz
- Practice Playground - run once