π₯ 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:
- Define who can access/use class members (variables/functions).
- 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
friendclasses/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
publicfor 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
- 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
- Visibility Hierarchy:
private<protected<public(most restrictive β least).
- Use Cases:
private: Internal implementation details.protected: Shared with subclasses.public: Safe external API.
- 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! π
