previous | start | next

## Encapsulation

- Classes are broken into `public` and `private` sections.
- The data items are defined in the `private` sections of the class definition.

  >     class Product
  >     {
  >     public:
  >        Product();
  >        void read();
  >        bool is_better_than(Product b) const;
  >        void print() const;
  >     private:
  >        string name;
  >        double price;
  >        int score;
  >     };

- Only constructors and member functions can access `private` data.
- Hiding data is called encapsulation.
- Encapsulation forces indirect access to the data, guaranteeing that it cannot accidentally be put in an incorrect state.
- Example:

  >     Time liftoff(19, 30, 0);
  >     /* liftoff is delayed by six hours */
  >     /* won't compile, but suppose it did */
  >     liftoff.hours = liftoff.hours + 6;

  Does this mean liftoff is at 25:30:00?

previous | start | next