Encapsulation
beginnerEncapsulation bundles data (attributes) and methods (functions) into a single unit (class) and restricts direct access to some components.
Why Encapsulate?
- Protect internal state from invalid changes
- Hide implementation details
- Provide controlled access through public methods
- Make code easier to maintain and refactor
Access Levels
- private: Only accessible within the class
- protected: Accessible in class and derived classes
- public: Accessible from anywhere
Example
You can't directly set balance = -1000 because it's private. The deposit() method validates the input.
Getters and Setters
Provide controlled access to private members with validation logic.
Mark every getter const so it can be called on a const object and to signal that it does not modify the object's state.
Key takeaway: Encapsulation protects internal state — use private members with public getters/setters to control access and validate inputs.