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 Standard
class 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.