Menu
Visibility in C++

Visibility in C++

πŸŽ₯ C++ Visibility: Access Modifiers Explained | Playlist

Playlist Link: C++ Series by TheCherno


πŸ“š Introduction to Visibility

Video Reference: Start at 0:00
Visibility modifiers (private, protected, public) control access to class members in C++. They:

  1. Define who can access/use class members (variables/functions).
  2. Enforce code organization (no runtime performance impact).

πŸ”’ Private Visibility

Video Reference: 1:38

class Entity {  
private: // πŸ‘ˆ Default for classes  
    int x, y;  

public:  
    Entity() { x = 0; } // βœ… Accessible within class  
};  

int main() {  
    Entity e;  
    e.x = 5; // ❌ Compile error: private member  
}  

Key Points:

  • Only accessible within the class (or friend classes/functions).
  • Default for class members.

πŸ›‘οΈ Protected Visibility

Video Reference: 3:00

class Entity {  
protected:  
    int x, y;  
};  

class Player : public Entity {  
public:  
    void Move() { x = 5; } // βœ… Accessible in subclass  
};  

int main() {  
    Player p;  
    p.x = 10; // ❌ Still private outside hierarchy  
}  

Key Points:

  • Accessible in class + subclasses.
  • Safer than public for inheritance hierarchies.

🌐 Public Visibility

Video Reference: 3:45

class Entity {  
public:  
    int x, y; // πŸ‘ˆ Default for structs  
};  

struct Vec2 {  
    int x, y; // βœ… Public by default  
};  

int main() {  
    Entity e;  
    e.x = 10; // βœ… Fully accessible  
}  

Key Points:

  • Accessible everywhere (class, subclasses, external code).
  • Default for struct members.

🎯 Why Use Visibility?

Video Reference: 4:30

  1. Encapsulation Example (UI Button):
    ```cpp
    class Button {
    private:
    int x, y;

public:
void SetPosition(int newX, int newY) {
x = newX;
y = newY;
RefreshDisplay(); // βœ… Extra logic
}
};

2. **Prevent Accidental Misuse:**  
   - Private members act as **documentation** ("Don't touch this!").  
   - Avoid direct variable access (use getters/setters).  

---

## ⚠️ **Common Pitfalls**  
1. **Default Visibility Confusion:**  
   - **Classes:** `private` by default.  
   - **Structs:** `public` by default.  

2. **Overusing Public Variables:**  
   ```cpp  
   class Player {  
   public:  
       int health; // ❌ Bad - no validation  
   };  

Better:

   class Player {  
   private:  
       int health;  
   public:  
       void TakeDamage(int dmg) {  
           if (dmg > 0) health -= dmg; // βœ… Validation  
       }  
   };  

πŸ“Œ Key Takeaways

  1. Visibility Hierarchy:
    • private < protected < public (most restrictive β†’ least).
  2. Use Cases:
    • private: Internal implementation details.
    • protected: Shared with subclasses.
    • public: Safe external API.
  3. Friends: Special exception to visibility rules (use sparingly).

πŸ”— Full Video: Visibility in C++


Need to revisit a concept? Jump directly to the video sections with the timestamped links above! πŸš€