liveBook · Manning

Encapsulation

As explained in 100 C++ Mistakes and How to Avoid Them

Encapsulation is the software design principle of containing an entity's data and behavior within its representation and controlling access to that representation.

Encapsulation contains a class's data and behavior, hides implementation details, and gives client code a controlled public interface. Its practical purpose is preserving the class invariant: every instance remains meaningful and predictable. section 7.2.1 section 9.12

A common mistake is writing accessors and mutators for every private variable. Trivial accessors expose representation, encourage clients to manage internal state, dilute essential methods, and make later changes harder. Expose behavior clients need rather than storage they can inspect. section 8.2

Apply encapsulation by:

  • Keeping state and the knowledge needed to validate it inside the class. section 7.2.1
  • Avoiding stored values that merely duplicate derived state; compute results through behavior when appropriate. section 8.2
  • Minimizing member functions that directly depend on representation, so a new representation changes fewer methods. section 9.12

Circle: expose computation, not cached representation

A Circle that stores both radius and area makes area an exposed implementation detail through getArea(). A safer form stores radius and computes radius*radius*PI in the accessor, avoiding duplicated state that can become inconsistent.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines implementation hiding, explains invariant protection, and works through accessors and member-function choices without pursuing language internals.
Examples
Uses Circle accessors and Date formatting and output functions to contrast exposed representation with computed behavior and minimized dependencies.
What it assumes
Assumes classes, instance variables, methods, and client code while developing the class invariant from their interaction.
What you can do after
Evaluate/understand whether class interfaces preserve invariants and permit representation changes without widespread client or method rewrites.
How it connects
Connects encapsulation to abstraction, class invariants, public interfaces, member functions, nonmember functions, and friend functions.

Also explained in

Compare how 14 books explain encapsulation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.