Encapsulation and abstraction
What you will learn on this page
Section titled “What you will learn on this page”- What encapsulation and abstraction each mean, and why they are two different ideas that work together.
- How to list the decisions in a problem that are likely to change, and hide each one inside a single class.
- Why a private data member with a public getter and setter is usually not encapsulation at all.
- How to choose the level an interface speaks at: not so low that callers repeat the rules, not so high that they lose choices they need.
- How to recognise a leaky abstraction in C++, and what to do about it.
- When plain public data is the right answer.
The problem
Section titled “The problem”An office has one heater, controlled by a thermostat. People can set the temperature from a panel on the wall or from a phone app. The facilities team writes down what the thermostat must do:
| ID | Requirement |
|---|---|
| FR-1 | A person sets a target temperature from 5 °C to 30 °C, both included. Anything outside that range is refused. |
| FR-2 | Each time the sensor reports the room temperature, the thermostat decides whether the heater runs. |
| FR-3 | Below the target by more than half a degree, the heater runs. Above it by more than half a degree, it stops. |
| FR-4 | Within half a degree of the target, the heater keeps doing what it was doing, so it does not switch on and off at every small change. |
| FR-5 | The wall panel and the phone app both show whether the heater is running. |
FR-4 describes a band around the target (sometimes called hysteresis). With a target of 21 °C, the band runs from 20.5 °C to 21.5 °C. A reading of 20.4 °C turns the heater on; a reading of 21.6 °C turns it off; anything from 20.5 °C to 21.5 °C, edges included, leaves it as it is.
The first version of the code was written quickly. It compiles, and both screens seem to work. But each screen applies its own copy of the heating rule, and the copies differ: at exactly 21.5 °C, the wall panel’s copy says “keep the heater on” and the phone app’s copy says “switch it off”. Whichever screen handled the last reading wins, and the two can show different states. This page explains why that happened, and how to design the thermostat so that it cannot.
Two ideas, one goal
Section titled “Two ideas, one goal”The two words are often used as if they meant the same thing. They answer different questions:
| Idea | The question it answers | What it gives callers | C++ tools |
|---|---|---|---|
| Abstraction | What does this thing do for the people who use it? | operations in their own words: “here is a reading”, “is the heater on?” | the choice of public member functions, their names, parameters, and results |
| Encapsulation | Who is allowed to change the data, and through which doors? | an object that is always valid, whatever they call | private data members, constructors that check, const queries, no references to internals |
Abstraction is about what you show. Encapsulation is about what you protect. A class can have one without the other:
- Encapsulation without a useful abstraction. All data is private, but
the public functions are just
get_band()andset_heater_on(bool). The data cannot be reached directly, yet every caller still has to know the heating rule. This is the first version of the thermostat. - Abstraction without encapsulation. A
structhas a nice function,bool needs_heat(double room) const, but its data members are public, so anyone can set the target to 80 °C. The rule exists, but the object can be made invalid.
What both serve is a third idea, usually called information hiding: put each decision that is likely to change inside one class, so that changing the decision changes only that class. (The term is usually traced to a 1972 paper by David Parnas on how to split a system into modules.) Encapsulation is how C++ enforces the hiding; abstraction is what the rest of the program sees instead.
Step 1: list the decisions likely to change
Section titled “Step 1: list the decisions likely to change”Before designing any class, write down the decisions in the problem that someone might change later, and who would ask for the change. For the thermostat:
| Decision | Who might change it | Must callers know it? |
|---|---|---|
| the heating rule: below the band on, above it off | the facilities team, the boiler maker | no |
| the size of the band (0.5 °C) | the facilities team, after complaints | no |
| what happens exactly at the edge of the band | whoever fixes the next bug | no |
| the allowed target range (5 °C to 30 °C) | the facilities team, building regulations | yes, to show it on the panel |
how temperatures are stored (double, tenths of a degree as int, …) |
a developer, for accuracy or a new sensor | no |
| how a reading arrives (the sensor, a test, a log file) | the hardware team | the callers provide it |
The rows marked “no” are decisions callers have no reason to know. Each one should live in exactly one place, inside the thermostat. The rows marked “yes” belong in the public interface, on purpose: the panel needs the range to show a slider, so the range is a public constant.
This table is the most useful habit on this page. A class is well encapsulated when every “no” row is private to it, and its abstraction is right when the public interface (functions and constants) covers every “yes” row and the callers’ needs, and nothing else.
Bad, good, great: who knows the heating rule?
Section titled “Bad, good, great: who knows the heating rule?”The move from “good” to “great” is the tell, don’t ask idea from finding classes. The callers stopped asking for the target and the band in order to decide for the thermostat, and started telling it the reading.
The two designs side by side
Section titled “The two designs side by side”class before::Thermostat
decides nothing
Data members
double target_ = 21.0;double band_ = 0.5;bool heater_on_ = false;
Member functions
double get_target() const;void set_target(double celsius);no checkdouble get_band() const;void set_band(double celsius);bool get_heater_on() const;void set_heater_on(bool on);
class Thermostat
owns FR-1 to FR-4
Data members
static constexpr double lowest_target = 5.0;public: the panel shows the rangestatic constexpr double highest_target = 30.0;publicstatic constexpr double band_ = 0.5;private: a hidden decisiondouble target_;bool heater_on_ = false;
Member functions
explicit Thermostat(double target_celsius);throws outside the rangevoid set_target(double celsius);same checkdouble target() const;void on_reading(double room_celsius);applies the rulebool heater_on() const;
Look at which functions disappeared and why:
| Removed | Why it went |
|---|---|
get_band, set_band |
No caller needs the band. It is a hidden decision, now a private constant. |
set_heater_on |
Only the rule decides whether the heater runs. Replaced by on_reading, which applies it. |
| (the two callers’ rules) | Moved into on_reading, once. |
And which stayed: target() and set_target stayed because a person really
does choose the target and the panel really does show it. heater_on()
stayed because FR-5 needs it. A getter is fine when a caller needs the
answer; the mistake is adding one for every field by habit.
This drawing shows the same change as who knows the rule:
Text description of the diagram
Two parts. Before: the wall panel box says “rule copy 1: greater than” and the phone app box says “rule copy 2: greater than or equal”. Each has a dashed “uses” arrow to before::Thermostat, labelled get_target, get_band, set_heater_on, get_heater_on. The thermostat box holds only target, band, and heater_on. After: the wall panel and the phone app each have a dashed “uses” arrow to Thermostat, labelled on_reading, heater_on, set_target. The Thermostat box holds target, heater_on, and the heating rule.
Diagram source (Mermaid)
flowchart LR
subgraph Before
P1["wall panel<br/>rule copy 1: >"] -.->|get_target, get_band,<br/>set_heater_on, get_heater_on| T1["before::Thermostat<br/>target, band, heater_on"]
A1["phone app<br/>rule copy 2: >="] -.->|get_target, get_band,<br/>set_heater_on, get_heater_on| T1
end
subgraph After
P2["wall panel"] -.->|on_reading, heater_on,<br/>set_target| T2["Thermostat<br/>target, heater_on,<br/>the heating rule"]
A2["phone app"] -.->|on_reading, heater_on,<br/>set_target| T2
endCheck: feed both designs the same readings
Section titled “Check: feed both designs the same readings”The example program gives the same five readings to the wall panel’s copy
of the rule, the phone app’s copy, and the new thermostat. To make the
disagreement visible, each screen’s copy works on its own
before::Thermostat object, so the program can show what each screen
would decide. The target is 21 °C in all three.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Five room temperatures, in order. 21.5 is exactly the top edge of the// band, where the two "before" copies of the rule disagree.const double readings[] = {20.0, 20.4, 21.2, 21.5, 21.6};
// One before::Thermostat per screen, so each copy of the rule has its// own heater state to show. Both start at target 21.0, band 0.5, off.before::Thermostat panel_view;before::Thermostat app_view;Thermostat thermostat{21.0}; // the "after" design, also target 21.0
std::cout << "room panel app after\n";for (const double room : readings) { // Every design gets the same reading. The "before" functions apply // the rule from outside; the "after" thermostat applies its own. before::wall_panel_reading(panel_view, room); before::phone_app_reading(app_view, room); thermostat.on_reading(room); // One row of the table. std::fixed and std::setprecision(1) print // one decimal place; std::left with std::setw(7) pads each column // to 7 characters. on_off turns true/false into "on"/"off". std::cout << std::fixed << std::setprecision(1) << std::left << std::setw(7) << room << std::setw(7) << on_off(panel_view.get_heater_on()) << std::setw(7) << on_off(app_view.get_heater_on()) << on_off(thermostat.heater_on()) << '\n';}room panel app after20.0 on on on20.4 on on on21.2 on on on21.5 on off on21.6 off off off
minute room heater0 20.0 on5 21.6 off8 20.3 off12 20.2 off15 20.1 onThe first table is this check. (The second table belongs to the requirement change later on the page.) Read it row by row:
- 20.0 °C is below 20.5 °C, so all three turn the heater on.
- 20.4 °C is still below the band. All on.
- 21.2 °C is inside the band, so all three keep the heater on.
- 21.5 °C is exactly the top edge. The panel (
>) and the new thermostat treat it as inside and keep the heater on. The app (>=) treats it as above and switches off. This is the bug. The two screens show different answers for the same heater. - 21.6 °C is above the band. All three switch off.
The new design cannot disagree with itself, because there is only one copy of the rule. Its tests check the heating rule, including both edges of the band, and the target range, including both ends:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_THROWS(expression, type) fails// unless the expression throws that type of exception. They come from the// site's small test header, lld_test.hpp.
// Target 21.0, so the band is 20.5 to 21.5. 20.4 is just below it.LLD_TEST(heats_when_the_room_is_below_the_band) { Thermostat t{21.0}; t.on_reading(20.4); LLD_CHECK(t.heater_on());}
// Both edges of the band count as inside, and inside means "no change":// on stays on at 21.5, and off stays off at 20.5.LLD_TEST(keeps_its_state_inside_the_band) { Thermostat t{21.0}; t.on_reading(20.0); // below the band: on t.on_reading(21.5); // exactly at the top edge: still inside LLD_CHECK(t.heater_on()); t.on_reading(21.6); // above the band: off LLD_CHECK(!t.heater_on()); t.on_reading(20.5); // exactly at the bottom edge: still inside LLD_CHECK(!t.heater_on());}
// set_target changes the target only. The heater, on after 20.0, stays on// until the next reading, which is judged against the new band (17.5 to// 18.5): 20.0 is above it, so the heater goes off.LLD_TEST(a_new_target_applies_from_the_next_reading) { Thermostat t{21.0}; t.on_reading(20.0); t.set_target(18.0); LLD_CHECK(t.heater_on()); // not switched by set_target itself t.on_reading(20.0); LLD_CHECK(!t.heater_on());}
// A refused target throws and leaves the thermostat as it was. Building a// Thermostat with a bad target throws too, so no object is created.LLD_TEST(a_target_out_of_range_is_rejected_and_the_old_one_kept) { Thermostat t{21.0}; LLD_CHECK_THROWS(t.set_target(45.0), std::out_of_range); LLD_CHECK_THROWS(Thermostat{-3.0}, std::out_of_range); LLD_CHECK(t.target() == 21.0);}
// 5.0 and 30.0 themselves are accepted; just past either end is refused.LLD_TEST(the_range_includes_both_ends) { Thermostat t{Thermostat::lowest_target}; t.set_target(Thermostat::highest_target); LLD_CHECK(t.target() == 30.0); LLD_CHECK_THROWS(t.set_target(30.5), std::out_of_range); LLD_CHECK_THROWS(t.set_target(4.5), std::out_of_range);}The edges can be tested with double here because the computed edges,
21.0 - 0.5 and 21.0 + 0.5, are exact in binary. With a target such as
21.3, 21.3 + 0.5 may not equal the literal 21.8 exactly, so a test at
the edge would need a tolerance. A real thermostat might store tenths of a
degree as an int, which avoids the question. In the “great” design that
change touches only the private members and on_reading; the callers
would not need editing as long as the public functions keep taking and
returning double.
Choosing the level of abstraction
Section titled “Choosing the level of abstraction”An interface speaks at a level. Too low, and every caller repeats the rules. Too high, and callers lose choices they need. The thermostat could have been designed at any of these three:
| Level | Interface | What goes wrong |
|---|---|---|
| too low | get_band(), set_heater_on(bool), get_target() |
Callers must know and repeat the rule. The class is a box of variables. |
| right | on_reading(double), heater_on(), set_target(double), target() |
Callers say what happened and read the result, in the words of the requirements. |
| too high | void keep_office_comfortable(), which reads the sensor itself, picks a target from a built-in schedule, and drives the heater |
Callers cannot choose the target (FR-1), tests cannot give it a reading, and a new sensor means rewriting the class. |
Three questions help you find the right level:
- Do the function names use the words of the requirements? “Reading”, “target”, “heater on” come from FR-1 to FR-5. “Band” appears only in the explanation of FR-4, as part of the rule, so it stays inside.
- Does any caller have to call two or more functions in a fixed order to
apply one rule?
get_target, thenget_band, thenset_heater_onis a rule spread across calls. Make it one function. - Is there a choice callers need that the class makes for them? If the panel cannot set the target, the level is too high. Let the caller pass the choice in.
The same thermostat can offer different levels to different callers. A building-management system might use a higher-level class that owns several thermostats and a schedule, built on top of this one. That is fine: each class speaks at one level, and the higher one uses the lower.
Leaky abstractions
Section titled “Leaky abstractions”An abstraction leaks when callers have to know something it was meant to hide in order to use it correctly. A leaky abstraction is not always a mistake (some leaks cannot be avoided), but each one is a place where a hidden decision has escaped. Common leaks in C++:
| Leak | Why it leaks | Fix |
|---|---|---|
std::vector<double>& readings() returns a non-const reference to a data member |
callers can change the history, and they depend on it being a std::vector |
return std::span<const double> (valid until the next change), or offer the query callers need (average_since) |
bool heater_on() documented as “true when relay pin 4 is high” |
callers now know the wiring | document the meaning (“the heater is running”), not the mechanism |
on_reading throws sensor_bus_error from a driver library |
the error type names the hardware, so callers must include its header | catch it inside and report in the class’s own terms, or let the sensor class handle it |
bool contains(...) that is fast for 10 items and slow for 10,000 |
callers had to know the container to know the cost | state the cost in a comment, or change the container behind the interface (CPP-12) |
the object is only valid after init() is called |
callers must know an order the class should enforce | do the work in the constructor, so a half-built object never exists (CPP-02) |
Two leaks are hard to avoid, and are best stated honestly in a comment:
cost (how long a call takes, how much memory it uses) and failure
(what can go wrong, especially with hardware, files, and networks). The
thermostat’s on_reading promises nothing about time because it is a few
comparisons; a function that talks to a network should say that it can be
slow and can fail.
Encapsulation tools in C++
Section titled “Encapsulation tools in C++”| Tool | What it protects | In the thermostat |
|---|---|---|
private data members |
no code outside the class can break an invariant directly | target_, heater_on_ |
| a constructor that checks | no invalid object can exist, even for a moment | explicit Thermostat(double) throws outside the range |
| one checked path for each change | every way to change a fact applies the same rule | the constructor and set_target share checked |
const queries |
reading cannot change the object’s visible state (barring mutable members) |
target(), heater_on() |
no non-const references or pointers to internals |
callers cannot change data behind the class’s back | target() returns a double by value |
an anonymous namespace in the .cpp |
helpers that are not part of the interface stay out of the header | checked in thermostat.cpp |
private constants |
numbers that are decisions, not facts callers need | band_ |
friend |
a deliberate, named exception (a closely tied class or operator) | not needed; use rarely |
Two more tools appear in later lessons. Interfaces (abstract base classes, CPP-10) hide which implementation is used, for example which sensor. The pimpl idiom hides even the private data members from the header, so that changing them does not recompile callers; that is an advanced technique with its own costs.
Harmful simple readings
Section titled “Harmful simple readings”A principle stated in one line is easy to misapply. Three readings of this one do more harm than good:
- “Make every data member private and add a getter and a setter.” As the “bad” design showed, that keeps the syntax of encapsulation and none of its value. Start from what callers need (MOD-12), not from the fields.
- “Never expose any data.” A plain record with no rules, such as a
reading with a time and a value, is clearer as a
structwith public members. Hiding it behind getters adds code and protects nothing. The requirement change below uses exactly such astructin its example program. - “Hide everything behind an interface.” An abstract base class with one implementation, made “in case”, hides nothing that a normal class would not, and makes the code harder to follow. Add an interface when there are two real implementations, or when tests need a substitute (PRN-04 covers this).
When not to
Section titled “When not to”Encapsulation earns its cost when there is a rule to protect or a decision to hide. Use plain public data when:
- The type is a value with no invariant. A point, a colour, a reading, a line in a report. Every combination of values is valid.
- The type carries data across a boundary. A message read from a file,
or the parameters for a function (a “parameter object”), is usually a
struct. Check it when it becomes a domain object, not before. - The code is a small, local helper. A
structinside one.cppfile, used by three functions, does not need a public interface.
Even then, keep the invariant somewhere. If a reading’s temperature must be between -50 °C and 60 °C, check it where readings enter the program, and give the checked value a type of its own if it travels far.
Trade-offs
Section titled “Trade-offs”| Benefit | Cost |
|---|---|
| One place to change each decision; the change cannot be missed elsewhere | Callers lose flexibility: a caller that really needs the band must ask for a new function |
| No invalid object can exist, so callers need no checks | More thought up front about what callers need |
| Tests check the rule once, at the class, not in every caller | A badly chosen abstraction is costly to change, because callers depend on it |
| Storage and algorithms can change without touching callers | Some leaks (cost, failure) cannot be hidden, only documented |
Common mistakes
Section titled “Common mistakes”- A getter and a setter for every field, added before any caller needs them.
- Returning a non-
constreference to a data member, which lets callers change it with no check. - Two paths to change one fact, one checked and one not (a checked
set_targetand an unchecked constructor). - Public functions named after the data (
get_band,set_heater_on) instead of after the job (on_reading). - An
init()function that must be called before the object works. - A
boolparameter that switches the rule off (“force”), which puts the decision back in the callers. - Hiding a plain record behind getters, so that every reader of the code must look in two places to see three numbers.
When a requirement changes
Section titled “When a requirement changes”The boiler maker sends a warning: switching the heater back on too soon after it stops can wear the boiler out. Once the heater switches off, it must stay off for at least ten minutes, even if the room cools below the band.
In the “bad” design, every caller would need to remember when the
heater last switched off. before::Thermostat has no place for that, so it
gains another field with another getter and setter, and both the wall panel
and the phone app gain the same new rule. If one of them forgets, or gets
the edge wrong again, the boiler could be damaged. A third caller, written next
year, must also know.
In the “great” design, the change is inside the thermostat. It gains a
private constant (minimum_rest_), a data member (switched_off_at_), and
a private helper (resting). on_reading gains two small edits: it skips
switching on while resting, and it records the time when it switches off.
The example keeps both versions so that both compile and can be compared,
so the changed thermostat is a second class, with_rest::Thermostat. In a
real project you would edit Thermostat itself.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The change: once the heater switches off, it must stay off for at least// ten minutes. Only the thermostat changes; callers now say when each// reading was taken.namespace with_rest {
class Thermostat {public: static constexpr double lowest_target = 5.0; static constexpr double highest_target = 30.0;
// Throws std::out_of_range unless lowest_target <= target <= highest_target. explicit Thermostat(double target_celsius);
void set_target(double celsius); [[nodiscard]] double target() const { return target_; }
// `now` is the time of the reading, from any fixed starting point. // Precondition: readings arrive in time order (not checked). // std::chrono::minutes is a count of whole minutes with its own type, so // a temperature (a double) cannot be passed by mistake where a time goes. void on_reading(double room_celsius, std::chrono::minutes now); [[nodiscard]] bool heater_on() const { return heater_on_; }
private: static constexpr double band_ = 0.5; static constexpr std::chrono::minutes minimum_rest_{10}; // a hidden decision
// True while fewer than minimum_rest_ minutes have passed since the // heater last switched off. Private: callers never need to ask. [[nodiscard]] bool resting(std::chrono::minutes now) const;
double target_; bool heater_on_ = false; // When the heater last went from on to off. std::optional holds either a // time or nothing; a new optional holds nothing (std::nullopt). std::optional<std::chrono::minutes> switched_off_at_; // empty: never switched off};
} // namespace with_restVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same band rule as before, with two small edits marked below.void Thermostat::on_reading(double room_celsius, std::chrono::minutes now) { if (room_celsius < target_ - band_) { // Edit 1: too cold, but switch on only if the rest period is over. // While resting, nothing changes: the heater stays off. (If it is // already on, it was not resting, so it simply stays on.) if (!resting(now)) heater_on_ = true; } else if (room_celsius > target_ + band_) { // Edit 2: remember the time, but only on a real switch from on to // off. A warm reading while already off must not restart the rest. if (heater_on_) switched_off_at_ = now; heater_on_ = false; } // Inside the band: keep the current state.}
// Reads as: "it has switched off at some time, and less than ten minutes// have passed since then". An empty optional converts to false, and `&&`// stops at a false left side, so *switched_off_at_ (the time inside the// optional) is read only when there is one. A thermostat that has never// switched off is not resting. Because the test is `<`, at exactly ten// minutes the rest is over.bool Thermostat::resting(std::chrono::minutes now) const { return switched_off_at_ && now - *switched_off_at_ < minimum_rest_;}How this code works: with_rest::Thermostat::on_reading and resting
on_reading still has the same three cases: below the band, above the
band, and inside it. Only two lines are new.
- Below the band (under 20.5 °C for a target of 21.0): the heater is
switched on only if
resting(now)is false. While resting, the branch does nothing, so the heater stays off. - Above the band (over 21.5 °C): before switching off, the code checks
whether the heater was on. Only a real change from on to off records
the time in
switched_off_at_. A warm reading while already off leaves the recorded time alone, so it cannot stretch the rest period. - Inside the band: neither branch runs, and nothing changes.
resting(now) is true only when both halves hold: switched_off_at_
holds a time (it has switched off at least once), and now minus that
time is less than 10 minutes. The && checks the left half first, so the
time inside the optional is read only when there is one.
A trace with the readings from the example program (target 21.0):
| Minute | Room | Branch | resting? |
Heater after | switched_off_at_ after |
|---|---|---|---|---|---|
| 0 | 20.0 | below band | no: never switched off | on | empty |
| 5 | 21.6 | above band | not asked | off | 5 (it was on) |
| 8 | 20.3 | below band | yes: 8 - 5 = 3 | off | 5 |
| 12 | 20.2 | below band | yes: 12 - 5 = 7 | off | 5 |
| 15 | 20.1 | below band | no: 15 - 5 = 10 | on | 5 |
At minute 15 the gap is exactly 10, and 10 < 10 is false, so the rest is
over. This matches the second table of the program’s output.
One thing does change for callers, and it is honest to say so: the rule
now needs the time of each reading, so on_reading gains a parameter of
type std::chrono::minutes. The decision (how long to rest, how to
remember the switch-off time) stayed hidden; a new input could not be.
The new input also brings a new precondition, written in the header:
readings must arrive in time order. It is not checked, which is a small
leak of its own. And because the parameter is in whole minutes, a caller
that measures in seconds must convert with std::chrono::duration_cast.
The type is a real time type, not an int, so a temperature cannot be
passed where a time is expected. If even that parameter must not reach the
callers, the thermostat can be given a clock object to ask instead, a
technique covered with dependency injection later in the course.
The example program gives this version five readings over 15 minutes:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
using std::chrono::minutes; // so `minutes` can be written alone below// A small local struct: one reading is a time and a room temperature.struct Reading { minutes at; double room;};const Reading day[] = { {minutes{0}, 20.0}, {minutes{5}, 21.6}, {minutes{8}, 20.3}, {minutes{12}, 20.2}, {minutes{15}, 20.1},};
with_rest::Thermostat resting_thermostat{21.0};std::cout << "\nminute room heater\n";for (const Reading& r : day) { // The caller now passes the time too: the one new input. resting_thermostat.on_reading(r.room, r.at); // r.at.count() is the plain number of minutes inside the duration. std::cout << std::left << std::setw(7) << r.at.count() << std::setw(7) << r.room << on_off(resting_thermostat.heater_on()) << '\n';}The second table in the output above shows the result. The heater switches off at minute 5. At minutes 8 and 12 the room is cold, but fewer than ten minutes have passed, so it stays off. At minute 15, exactly ten minutes later, it runs again. The tests check the edge (9 minutes is too soon, 10 is enough) and that the very first switch-on does not wait:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The edge of the rest period: 9 minutes after switching off is too soon,// and exactly 10 minutes is enough (resting() uses `<`).LLD_TEST(stays_off_for_the_minimum_rest_after_switching_off) { using std::chrono::minutes; with_rest::Thermostat t{21.0}; t.on_reading(20.0, minutes{0}); // cold: on t.on_reading(21.6, minutes{5}); // switches off at minute 5 t.on_reading(20.0, minutes{14}); // cold, but only 9 minutes later LLD_CHECK(!t.heater_on()); t.on_reading(20.0, minutes{15}); // 10 minutes: rest is over LLD_CHECK(t.heater_on());}
// switched_off_at_ starts empty, so a thermostat that has never switched// off is not resting, even at minute 0.LLD_TEST(the_first_switch_on_does_not_wait) { with_rest::Thermostat t{21.0}; t.on_reading(19.0, std::chrono::minutes{0}); LLD_CHECK(t.heater_on());}Exercise: Review an over-exposed class
A shop’s checkout code has this class. The rules are: the total is always
the sum of the lines, less the discount; the discount is between 0 and 50
percent; and once a cart is checked out, nothing in it may change. Assume
Money is a value type that counts cents, and Line is a struct with a
product ID, a quantity, and a unit price.
// The class to review. Read each member as "what can a caller do with it?".class Cart {public: // Returns a reference (&) to the cart's own vector of lines, not a copy, // so whatever the caller does to it happens to the cart's lines. std::vector<Line>& lines(); void set_total(Money total); // stores the total the caller passes in Money total() const; void set_discount_percent(int percent); // stores the percent it is given int discount_percent() const; // A public data member: any caller can read it or assign to it. bool checked_out = false;};- List every way a caller can break one of the three rules.
- Which decisions does this class expose that callers should not need to know?
- Write a class outline for a better
Cart. For each public member function, name the caller need it serves. - Which part of your design would you keep as a plain
struct, and why?
Show the explained answer
1. Ways to break the rules.
| Call | Rule broken |
|---|---|
cart.lines().push_back(...) |
the total no longer matches the lines |
cart.set_total(Money{0}) |
the total no longer matches the lines |
cart.set_discount_percent(90) |
the discount is above 50 percent |
cart.lines().clear() after checkout |
nothing may change after checkout |
cart.checked_out = false; |
a checked-out cart becomes changeable again |
cart.set_discount_percent(20) |
the stored total no longer includes the discount |
cart.set_discount_percent(-5) |
the discount is below 0 percent |
set_total or set_discount_percent after checkout |
nothing may change after checkout |
| changing a line’s quantity to 0 or -2 through the reference | (a fourth rule, probably: quantities are positive) |
2. Exposed decisions. That the lines are stored in a std::vector;
that the total is stored rather than computed; that “checked out” is a
bool (it might later be a state with more values, such as “paid” or
“refunded”).
3. One better design.
class Cart
owns the three rules
Data members
std::vector<Line> lines_;int discount_percent_ = 0;bool checked_out_ = false;static constexpr int max_discount_percent = 50;
Member functions
[[nodiscard]] bool add(ProductId product, int quantity, Money unit_price);false after checkout; throws if quantity <= 0[[nodiscard]] bool remove(ProductId product);false after checkout or if absent[[nodiscard]] bool set_discount(int percent);false after checkout; throws outside 0 to 50Money total() const;computed from lines_ every time; discount rounded to the nearest centstd::span<const Line> lines() const;read-only, for the receipt; valid until the next add or remove[[nodiscard]] bool check_out();false if already checked outbool checked_out() const;
struct Line
value: no rules beyond those Cart applies
Data members
ProductId product;int quantity;Money unit_price;
| Function | Caller need |
|---|---|
add, remove |
the shopper changes the cart |
set_discount |
the cashier applies a voucher |
total() |
the screen and the payment step show the amount |
lines() |
the receipt lists the items |
check_out, checked_out() |
the payment step closes the cart; the screen disables editing |
There is no set_total: the total is derived data, computed from the
lines, so it can never disagree with them. If computing it became too slow
(unlikely for a cart), the class could cache it privately and nothing
outside would change. Wrong discounts and bad quantities are bugs in the
calling code, so they throw; a change after checkout is a normal refusal
the screen shows, so it returns false. That holds even though the
screen uses checked_out() to disable editing: a second till, or a
shopper with two browser tabs, can still send a change after checkout, so
the refusal is a normal event, not a bug. A reasonable alternative is an
enum class result that says why a change was refused.
Three decisions the problem does not settle, which you should ask about: how the discount is rounded to whole cents; whether adding a product that is already in the cart adds to its quantity or adds a second line; and whether an empty cart may be checked out.
4. The plain struct. Line stays a struct. It has no rule of its own
that Cart does not already apply, and callers only read it, through a
std::span<const Line>. Giving it getters would add code and protect
nothing.
Summary
Section titled “Summary”- Abstraction chooses what callers see: operations in the words of the requirements. Encapsulation protects the data so the object is always valid. Both serve information hiding: each decision likely to change lives in one class.
- Start by listing the decisions likely to change and asking, for each, whether callers must know it. Everything they need not know is private.
- A getter and a setter for every field is public data with extra typing. Replace the setters with operations that apply the rules, and keep only the getters some caller needs.
- Choose the level of an interface by its callers: no rule repeated in them, no choice they need taken away.
- An abstraction leaks when callers must know what it hides. Fix the leaks you can; document cost and failure, which you often cannot hide.
- Plain
structs are right for values and records with no rules. - When a requirement changes, a well-encapsulated class absorbs the decision; a new input may still have to reach it, and that is honest.