C++ ยท Chapter 35 of 49

C++ Encapsulation

Encapsulation means bundling data and the methods that operate on it together, while restricting direct access to internal state. It's achieved in C++ by marking fields `private` and exposing controlled access through public methods.

This protects the object's invariants โ€” for example, ensuring a bank balance never becomes negative โ€” because all changes must go through validated methods.

Why encapsulate?

Hiding internal representation lets you change how data is stored internally without breaking code that uses the class, as long as the public interface stays the same.

Validating input

A setter method can reject invalid values, e.g. refusing to set a negative age, something a public field alone can't enforce.

Example 1 (cpp)
class Person {
private:
    int age;
public:
    void setAge(int a) { if (a >= 0) age = a; }
    int getAge() { return age; }
};
int main() {
    Person p;
    p.setAge(-5);
    p.setAge(30);
    std::cout << p.getAge();
}
Output
30

setAge() rejects the invalid -5 and only accepts the valid 30.

Key points

  • Encapsulation hides internal state behind a controlled interface.
  • Private fields plus public getters/setters is the classic pattern.
  • It protects an object's invariants from invalid states.
  • Internal representation can change without breaking external code.
๐Ÿ’ก Note: Avoid trivial getters/setters that expose everything unrestricted โ€” that defeats the purpose of encapsulation.

๐Ÿ“ Quick Quiz

1. Encapsulation is mainly about:

2. What pattern commonly implements encapsulation?

3. A benefit of encapsulation is: