C++ Classes vs Structs Notes
By The Cherno | Full Playlist π
1. Key Difference: Default Visibility
π Only Technical Difference:
class: Members are private by default.struct: Members are public by default.
Example:
// Class (private by default)
class Player {
int x, y; // Private
public:
void move() { /* ... */ } // Public
};
// Struct (public by default)
struct Vec2 {
float x, y; // Public
void add(const Vec2& other) { /* ... */ } // Public
};
2. When to Use Struct vs Class
Struct Usage:
- Plain Old Data (POD): Group related variables (e.g.,
Vec2,Color). - No complex functionality: Avoid inheritance; focus on data storage.
struct Vec2 { float x, y; void add(const Vec2& other) { x += other.x; y += other.y; } };
Class Usage:
- Complex objects: Combine data + methods (e.g.,
Player,GameWorld). - Inheritance: Use for class hierarchies.
class Player { private: int health; public: void attack() { /* ... */ } };
3. Backward Compatibility with C
- Structs exist in C: C++ retains
structfor compatibility. - C code: Replace
structwithclass+publicto compile in C++.
Example:
// C code
struct Point {
int x, y; // Public in C
};
// Equivalent C++ code
class Point {
public:
int x, y;
};
4. Best Practices
- Use
structfor data containers:struct Transform { float position[3]; float rotation[3]; }; - Use
classfor complex logic:class Enemy : public Character { private: int damage; public: void attack() { /* ... */ } }; - Avoid mixing inheritance:
- Compilers warn if a
structinherits from aclass.
- Compilers warn if a
Cheat Sheet
| Feature | Class | Struct |
|βββββββββ|ββββββββββββ|ββββββββββββ-|
| Default Visibility | private | public |
| Typical Use Case | Complex objects, inheritance | Data grouping (POD) |
| Inheritance | Preferred for hierarchies | Avoid |
| Full Video π | Playlist π |
π‘ Pro Tip: Use struct for simple data bags and class for objects with behavior. Keep code readable!
