Menu
Classes vs Structs in C++

Classes vs Structs in C++

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  
};  

Video Reference πŸŽ₯


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() { /* ... */ }  
    };  
    

    Video Reference πŸŽ₯


3. Backward Compatibility with C

  • Structs exist in C: C++ retains struct for compatibility.
  • C code: Replace struct with class + public to compile in C++.

Example:

// C code  
struct Point {  
    int x, y; // Public in C  
};  

// Equivalent C++ code  
class Point {  
public:  
    int x, y;  
};  

Video Reference πŸŽ₯


4. Best Practices

  1. Use struct for data containers:
    struct Transform {  
        float position[3];  
        float rotation[3];  
    };  
    
  2. Use class for complex logic:
    class Enemy : public Character {  
    private:  
        int damage;  
    public:  
        void attack() { /* ... */ }  
    };  
    
  3. Avoid mixing inheritance:
    • Compilers warn if a struct inherits from a class.

Video Reference πŸŽ₯


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!