C++ Classes Notes
By The Cherno | Full Playlist đź”—
1. What are Classes?
📌 Key Idea: Classes group data (variables) and functionality (methods) into reusable blueprints.
- Purpose: Organize code, model real-world entities (e.g.,
Player,Car). - Object: An instance of a class (e.g.,
Player player1;).
Example Without Classes (Messy Variables):
int playerX, playerY; // Position
int playerSpeed = 2;
void move(int& x, int& y, int speed) { /* ... */ }
With Classes (Organized):
class Player {
public:
int x, y, speed;
void move(int xa, int ya) {
x += xa * speed;
y += ya * speed;
}
};
2. Creating a Class
Syntax:
class ClassName {
// Data (variables) and methods (functions)
};
Example:
class Player {
public:
int x = 0, y = 0;
int speed = 2;
};
- Instantiate an object:
Player player1; player1.x = 5; // Access member variables
3. Visibility: Public vs. Private
public: Accessible outside the class.private(default): Accessible only inside the class.
Example:
class Player {
public: // Accessible anywhere
int x, y;
private: // Accessible only inside Player
int health = 100;
};
- Error:
player1.health = 50;❌ (private member).
Video Reference 🎥
4. Methods (Class Functions)
Methods are functions inside a class that operate on the class’s data.
Standalone Function vs. Class Method:
// Standalone function (before classes)
void move(Player& player, int xa, int ya) {
player.x += xa * player.speed;
}
// Class method (cleaner!)
class Player {
public:
void move(int xa, int ya) {
x += xa * speed; // Direct access to x, speed
}
};
Usage:
Player player1;
player1.move(1, -1); // Moves player1
5. Key Takeaways
- Classes group related data + logic: Avoid scattered variables.
- Objects are instances:
Player player1;creates aPlayerobject. - Encapsulation: Use
public/privateto control access. - Methods simplify code: Replace standalone functions with class methods.
Remember: Classes are syntactic sugar for code organization—they don’t add new functionality, just structure!
| Full Video đź”— | Playlist đź”— |
đź’ˇ Pro Tip: Use classes to model entities in your code (e.g., Enemy, Inventory) for cleaner, maintainable projects!
