C++ - Encapsulation

Overview

Estimated time: 25–35 minutes

Hide internal representation and expose a minimal stable interface. Preserve invariants through controlled access.

Learning Objectives

  • Design classes with private data and public functions.

Example

class BankAccount{
  double balance{0.0};
public:
  void deposit(double x){ if (x>0) balance+=x; }
  double get() const { return balance; }
};

Common Pitfalls

  • Exposing mutable fields breaks invariants and decoupling.