Core Module
12 min forge
C++ Encapsulation
Wrapping data and functions into a single unit and restricting access.
C++ Encapsulation
π What is it
Encapsulation is the process of bundling data (variables) and the methods that operate on them into a single unit (Class). It also involves hiding internal details using access specifiers (private, protected).
β‘ When to use
Always! Use encapsulation to protect your data from being modified directly by external code and to enforce valid states (e.g., using setAge() with validation).
π§ Time complexity
- Member Access: $O(1)$.
π» Code example
cpp Standardclass Employee { private: int salary; // Hidden public: void setSalary(int s) { if (s > 0) salary = s; // Validation } int getSalary() { return salary; } };
β Common mistakes
- Making all members
public(defeats the purpose). - Not providing getters/setters for data that should be read/modified.
- Exposing internal implementation details in the public interface.