Lesson 139 +10 XP

Encapsulation

Encapsulation

Encapsulation is about hiding an object's details and exposing safe, controlled ways to work with it. In C++ you hide data with private members and give the outside world getters (to read) and setters (to write).

Why hide the data

If a member is public, any code can set it to anything, even nonsense:

car.year = -300;     // nonsense value, nothing stops it

Making data private and funneling changes through a method keeps objects consistent.

Getters and setters

class Car {
private:
  int year;
public:
  void setYear(int y) {
    if (y > 1885) {          // validation before storing
      year = y;
    }
  }
  int getYear() {
    return year;
  }
};
  • getYear() reads the private value.
  • setYear() feeds the new value through a check before storing it.

Controlled access

Callers never touch the private member directly. They only see getYear() and setYear(), so the class keeps full control over what ends up inside.

TL;DR

  • Encapsulation = hide the data (private members) and control access.
  • Getters read; setters write, with validation if needed.
  • This prevents invalid states and keeps a safe interface.