Modern C++ • C++20 baseline
Classes, Encapsulation, and Invariants
Use a class when the type must protect rules about its internal state.
Encapsulation lets a type control how its state changes. A class should make invalid states difficult to construct and expose operations that preserve its invariant. Keep public interfaces small and keep implementation details private until callers have a real need for them.
Key points
- A class defaults to private member access.
- Invariants should be established by construction and maintained by every public operation.
Example
#include <stdexcept>
class Percentage {
public:
explicit Percentage(int value) : value_(value) {
if (value < 0 || value > 100) {
throw std::out_of_range("percentage must be between 0 and 100");
}
}
int value() const noexcept { return value_; }
private:
int value_;
};
What to expect
A Percentage object can only be created with a value between 0 and 100.
Practice exercise
Add a function that combines two percentages. Decide whether the result should clamp, reject, or use a wider domain.
Key idea: A class is valuable when it owns an invariant or resource, not simply because the language supports classes.