Composition-based alternatives to inheritance-heavy patterns
What you will learn on this page
Section titled “What you will learn on this page”- How to tell what a base class is really for in a design: an extension point, a closed list of variants, a fixed loop with one varying step, or code reuse.
- Four C++ tools that do each of those jobs without a class hierarchy:
std::function,std::variant, a function template, and delegation. - What each tool costs, who owns what with each, and when a virtual interface is still the better choice.
The problem
Section titled “The problem”A text editor lets extensions act when a document is saved.
- FR-1. Extensions run before the save, and may change the text that is written, or after it, and see the saved text. They run in the order they were added.
- FR-2. Users choose cleanup rules in a settings file:
trim(remove trailing spaces),tabs:N(replace tabs with spaces), andcollapse-blank(one blank line where there were several). The settings screen lists the chosen rules back to the user. - FR-3. Any combination of extensions can be used, including ones written by other teams, such as a word count shown in the status bar.
- FR-4. The editor keeps the last few saved versions, never more than a limit, so that a user can compare with an earlier save.
The open document must not be changed by a save: extensions work on the copy that is written.
The inheritance-heavy version
Section titled “The inheritance-heavy version”The first design uses inheritance for everything:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every extension is a class derived from one base, overriding the hooks// it needs; the others stay empty.// The editor calls before_save on each plugin to change the document,// then after_save once the text is ready. A plugin that only wants one// hook still inherits the other, as a function that does nothing.class EditorPlugin {public: virtual ~EditorPlugin() = default; // Virtual with an empty body `{}`, not pure virtual: a derived class may // override it, but does not have to. virtual void before_save(Document&) {} virtual void after_save(const Document&, const std::string& /*text*/) {}
// `= delete` forbids copying. A plugin is used through a base-class // pointer, and copying through the base would copy only the base part // (slicing), so copies are ruled out. EditorPlugin(const EditorPlugin&) = delete; EditorPlugin& operator=(const EditorPlugin&) = delete;
protected: // Protected: only a derived class can construct an EditorPlugin, so no // one makes a bare plugin that does nothing at all. EditorPlugin() = default;};
// A Template Method: before_save walks the lines, and each derived class// says what to do with one line.// The fixed part is the loop "for each line, call edit_line(line)"; the// varying part is edit_line. So every line edit has to be a class.class LinePlugin : public EditorPlugin {public: // `final` on a function: no class below LinePlugin may override it, so // the loop cannot be replaced, only the step inside it. void before_save(Document& document) final;
private: // Pure virtual, so each derived class must supply it. Private, so code // outside cannot call it: the loop in before_save is what calls it. virtual void edit_line(std::string& line) = 0;};
// Removes the spaces and tabs at the end of each line.class TrimPlugin : public LinePlugin { // not final: TrimAndCountPlugin reuses itprivate: void edit_line(std::string& line) override;};
// Replaces tabs with spaces, up to the next multiple of width.class ExpandTabsPlugin final : public LinePlugin {public: explicit ExpandTabsPlugin(int width); // throws std::invalid_argument below 1
private: void edit_line(std::string& line) override; int width_;};
// Works on the whole list of lines, not one line at a time, so it cannot// use LinePlugin's loop and overrides before_save itself.class CollapseBlankLinesPlugin final : public EditorPlugin {public: void before_save(Document& document) override;};
// Derives from TrimPlugin only to reuse its trimming. Counting without// trimming needs another class, and so does every other combination.// Its before_save trims (inherited from LinePlugin and TrimPlugin); its// after_save stores the word count of the saved document.class TrimAndCountPlugin final : public TrimPlugin {public: void after_save(const Document& document, const std::string& text) override; std::size_t words() const { return words_; } // 0 until the first save
private: std::size_t words_ = 0;};
// Derives from a container to reuse it. add keeps at most limit versions,// but the inherited push_back, insert, and resize do not.// Public inheritance makes every std::vector function part of this class,// so any caller can break the limit. add only drops the oldest when the// size is exactly equal to the limit, so once the size has gone past it,// add never drops anything again (the test below shows this).class SavedVersions : public std::vector<std::string> {public: explicit SavedVersions(std::size_t limit); // throws std::invalid_argument for 0 // If full, erases the first (oldest) text, which shifts every other // element down by one, then appends the new one. void add(std::string text);
private: std::size_t limit_;};
// The editor owns its plugins (std::unique_ptr) and runs them in the// order they were added: every before_save, then join the lines into the// text, then every after_save. save returns that text.class Editor final {public: // Takes ownership: the caller hands over the unique_ptr with std::move // or std::make_unique, and the editor deletes the plugin when it dies. void add(std::unique_ptr<EditorPlugin> plugin); // throws std::invalid_argument if null // `document` is taken by value, so the caller's document is never changed. std::string save(Document document) const; // the plugins change this copy
private: std::vector<std::unique_ptr<EditorPlugin>> plugins_;};It works, and the tests confirm that it saves exactly the same text as the version later on this page. But each class exists for a different reason, and inheritance is a poor fit for most of them:
EditorPluginis an extension point with empty hooks. Each extension overrides one function and inherits an empty one. A word count, which is one line of code, needs a class, a header, and astd::make_unique.LinePluginis a Template Method for a loop. The fixed part is three lines, “for each line, edit it”; the varying part is one function. Every line edit must become a class to reuse those three lines.TrimAndCountPluginderives fromTrimPluginonly to reuse it. It is a combination of two extensions written as a subclass. Every other combination would need another class, and the word count cannot be used without trimming.- The cleanup rules are classes, but they are really settings.
FR-2 asks to read them from a file and list them back. A
std::unique_ptr<EditorPlugin>cannot say which setting it came from, cannot be compared (“istrimalready on?”), and cannot be copied. SavedVersionsderives fromstd::vectorto reuse it. Itsaddkeeps the limit, but everythingstd::vectoroffers is also public. This test, against the before-version, passes:
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_EQ(actual, expected) fails if// the two values differ, 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.
// Proves the inherited std::vector functions get around the limit. With a// limit of 2, two adds fill it; push_back, inherited from std::vector,// makes the size 3. From then on add only drops the oldest when the size// equals 2, which it never will again, so the next add makes the size 4.LLD_TEST(before_versions_let_the_inherited_functions_break_the_limit) { before::SavedVersions versions{2}; versions.add("a"); versions.add("b"); versions.push_back("c"); // compiles: push_back is inherited LLD_CHECK_EQ(versions.size(), std::size_t{3}); versions.add("d"); // size is no longer equal to the limit, so nothing is dropped LLD_CHECK_EQ(versions.size(), std::size_t{4}); LLD_CHECK_THROWS(before::SavedVersions{0}, std::invalid_argument);}
// Sets up the same three cleanups in both designs and proves they write// the same text. The document has trailing spaces, tabs, two blank lines// in a row (the second is only spaces), and a tab inside a line. It also// checks that both designs refuse bad input: a null plugin and a tab// width of 0.LLD_TEST(the_two_designs_save_the_same_text) { const Document notes{"n", {"\tbuy milk ", "", " ", "call ana\t", "x\ty"}};
before::Editor old_editor; old_editor.add(std::make_unique<before::TrimPlugin>()); old_editor.add(std::make_unique<before::ExpandTabsPlugin>(2)); old_editor.add(std::make_unique<before::CollapseBlankLinesPlugin>()); LLD_CHECK_THROWS(old_editor.add(nullptr), std::invalid_argument); LLD_CHECK_THROWS(before::ExpandTabsPlugin{0}, std::invalid_argument);
// The hook design: each setting is parsed into a rule, and the lambda // keeps its own copy of the rule ([rule = ...] makes a new captured // variable from that expression). Editor editor; for (const std::string setting : {"trim", "tabs:2", "collapse-blank"}) { editor.before_save([rule = parse_cleanup(setting)](Document& document) { apply(rule, document); }); } LLD_CHECK_EQ(old_editor.save(notes), editor.save(notes));
// TrimAndCountPlugin trims and counts; the hook design adds two hooks. // `counter` is a reference to the plugin, taken before the unique_ptr // is moved into the editor. Moving hands over ownership but does not // move the plugin object itself, so the reference stays valid for as // long as counting_editor keeps the plugin alive. before::Editor counting_editor; auto plugin = std::make_unique<before::TrimAndCountPlugin>(); const before::TrimAndCountPlugin& counter = *plugin; counting_editor.add(std::move(plugin)); // save's returned text is not needed here, only the count it leaves. // Trimming removes no words, so the count matches the original notes. counting_editor.save(notes); LLD_CHECK_EQ(counter.words(), word_count(notes));}The first test shows the invariant broken. After one push_back,
add no longer drops anything, because it only checks for a size
equal to the limit. FR-4 is broken by a line that compiled without
a warning.
Step 1: name what each base class is for
Section titled “Step 1: name what each base class is for”Before replacing anything, say what each use of inheritance actually needs. The answer picks the tool:
| In the before-version | What it really needs | Tool that fits |
|---|---|---|
EditorPlugin |
an open list of actions, each one call, added at run time | std::function, stored in a list |
| the three cleanup classes | a closed set of named options, read from and shown as text | std::variant of small structs |
LinePlugin |
a fixed loop with one varying step, used during one call | a function template |
TrimAndCountPlugin |
two extensions used together | add both; no new type at all |
SavedVersions |
a container’s storage, behind a smaller interface | delegation: hold it, and forward |
One gap in the first row: an extension that needs both hooks and
shared state registers two lambdas that borrow one object, as words
does below. When extensions routinely need several related hooks,
that is a role, and an interface fits better.
The sections below take these in turn. Each tool keeps one benefit of the base class it replaces and drops the coupling that came with it.
Tool 1: std::function for an open set of hooks
Section titled “Tool 1: std::function for an open set of hooks”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Extensions are functions, not classes. Each hook is any callable with the// right signature: a lambda, a function, or an object with operator().// The editor owns a copy of each hook, and runs them in the order added.class Editor final {public: // std::function<void(Document&)> can hold any callable that can be // called with a Document&; anything it returns is ignored. It keeps its own copy // of the callable, including anything the callable captured by value. // A before-save hook may change the document; an after-save hook only // reads it, together with the joined text that will be saved. using BeforeSave = std::function<void(Document& document)>; using AfterSave = std::function<void(const Document& document, const std::string& text)>;
// Throw std::invalid_argument for an empty hook, and std::logic_error // if called from a hook while save is running. // The hook is taken by value and moved into the list. void before_save(BeforeSave hook); void after_save(AfterSave hook);
// Runs the before-save hooks on a copy of the document, joins its // lines, runs the after-save hooks, and returns the saved text. // Throws std::logic_error if called from one of its own hooks. std::string save(Document document);
private: // Throws std::logic_error, naming `function`, if save is running. void refuse_while_saving(const char* function) const;
std::vector<BeforeSave> before_; std::vector<AfterSave> after_; bool saving_ = false; // the hook vectors must not change while they run};A hook is now any callable with the right signature. Nothing derives from anything. The editor keeps two lists and runs them in order:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Adds a before-save hook to the end of the list. Checks come first, so a// refused hook leaves the list unchanged.void Editor::before_save(BeforeSave hook) { refuse_while_saving("before_save"); // An empty std::function (for example, one made from nullptr) holds no // callable and converts to false; calling it would throw // std::bad_function_call, so it is refused here instead. if (!hook) { throw std::invalid_argument{"before_save: empty hook"}; } // std::move hands the callable to the vector without copying it. before_.push_back(std::move(hook));}
// The same, for the after-save list.void Editor::after_save(AfterSave hook) { refuse_while_saving("after_save"); if (!hook) { throw std::invalid_argument{"after_save: empty hook"}; } after_.push_back(std::move(hook));}
// `document` is a copy (taken by value), so the hooks change only this// copy; the caller's document is left as it was.std::string Editor::save(Document document) { refuse_while_saving("save"); // a hook calling save again is refused too saving_ = true; // Clears the flag however save ends, even if a hook throws. // A small struct defined right here: it holds a reference to saving_, // and its destructor sets it back to false. `reset` is a local object, // so its destructor runs when save returns or when an exception leaves // it (RAII: the cleanup is tied to an object's lifetime). struct Reset { bool& flag; ~Reset() { flag = false; } } const reset{saving_};
// Each hook in the order it was added; each sees the changes of the // ones before it. for (const BeforeSave& hook : before_) { hook(document); } std::string text = joined(document); // every line followed by '\n' for (const AfterSave& hook : after_) { hook(document, text); } return text;}
// The guard every public function calls first. While saving_ is true, a// hook that calls before_save, after_save, or save on this editor gets an// exception instead of changing a list that is being looped over.void Editor::refuse_while_saving(const char* function) const { if (saving_) { // std::string{function} turns the character pointer into a // std::string, so + can join the two parts of the message. throw std::logic_error{std::string{function} + ": not allowed from a hook during save"}; }}How this code works: Editor::save and its guard
- Refuse a nested save.
refuse_while_saving("save")throwsstd::logic_errorif a save is already running, which can only happen when one of the hooks callssaveon this editor. - Raise the flag.
saving_ = true. From now on,before_save,after_save, andsaveall throw at their first line, so no hook can changebefore_orafter_while the loops below walk them. - Arm the reset.
resetis a small local object holding a reference tosaving_. Its destructor sets the flag back tofalse, and C++ runs that destructor howeversaveends: by thereturn, or by an exception thrown from a hook. - Run the before-save hooks in the order they were added, each on
the same
document, so each one sees what the earlier ones did.documentis the function’s own parameter, taken by value, so the hooks never change a document the caller still uses (the example passesnotes, which is copied). - Join the lines into
text, each line followed by'\n'. - Run the after-save hooks with the finished document and text.
- Return the text.
resetis destroyed on the way out, and the editor is ready for the next save.
Why the flag matters: if a hook called before_save during the loop,
push_back could make the vector move its elements to new memory. The
loop’s position, and the std::function that is running, would then
refer to memory that has been freed. Refusing the call turns that
undefined behaviour into a clear exception.
If a hook throws, the exception passes out of save to the caller, the
remaining hooks do not run, nothing is returned, and the flag is still
cleared, so the next save works.
class Editor final
no base class; holds its hooks by value
Data members
std::vector<BeforeSave> before_;owned copies of the callables, in the order addedstd::vector<AfterSave> after_;bool saving_;true during save: the lists must not change while they runvoid refuse_while_saving(const char* function) const;private: throws std::logic_error
Member functions
void before_save(BeforeSave hook);refuses an empty hookvoid after_save(AfterSave hook);std::string save(Document document);works on its own copy; returns the saved text
Ownership. A std::function owns a copy of the callable it is
given, together with everything that callable captured by value.
Anything captured by reference is only borrowed, exactly like a
raw pointer: the word-count hook captures &words, so words must
outlive the editor. The usage below declares it first for that
reason.
Re-entrancy. A hook could capture the editor itself and add a hook
during save. push_back might reallocate the list being looped
over, which invalidates the loop’s iterators and can destroy the very
std::function that is running: undefined behaviour either way.
(Adding to the other list would be safe, but the editor refuses both
for simplicity.) The editor refuses this
with a flag, as the Mediator room refuses
join while delivering. A small local struct resets the flag however
save ends, so one failed save does not lock the editor.
What std::function costs:
- Type erasure. Each call goes through an indirect call, much like
a virtual call, and a callable that the library will not keep in
the
std::functionobject’s internal buffer, because it is too large or (in some implementations) not trivially copyable, is allocated on the heap. Which callables fit depends on the standard library; with libstdc++, a lambda that captures astd::stringis already allocated. For hooks that run once per save, neither cost matters; for a call made millions of times in a tight loop, measure. - It must be copyable. A lambda that captures a
std::unique_ptrcannot be stored in astd::function. - Hooks have no names. You cannot ask a hook what it is, list the
active extensions, or remove one. If FR-1 grows “disable an
extension”,
before_saveshould return a handle, like the Observer page’sSubscription, or the editor should store a name with each hook.
Tool 2: std::variant for a closed set of values
Section titled “Tool 2: std::variant for a closed set of values”The cleanup rules are not extensions: they are three known options
with a little data each. That is what a std::variant of small
structs expresses:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The cleanup rules a settings file can name. The set is closed: adding a// rule means editing this file, and the compiler then reports every// std::visit that does not handle it. Each rule is a plain value: it can// be copied, compared, and turned back into its setting.// A rule with no settings is an empty struct: its type alone says which// rule it is. Two TrimTrailing values are always equal.struct TrimTrailing { bool operator==(const TrimTrailing&) const = default;};
struct ExpandTabs { int width = 4; // parse_cleanup gives 1 to 8 bool operator==(const ExpandTabs&) const = default;};
struct CollapseBlankLines { bool operator==(const CollapseBlankLines&) const = default;};
// A Cleanup holds exactly one of the three rules. Two Cleanups are equal// when they hold the same kind of rule with equal members: a Cleanup// holding ExpandTabs{2} equals another holding ExpandTabs{2}, but not one// holding ExpandTabs{4} or TrimTrailing{}.using Cleanup = std::variant<TrimTrailing, ExpandTabs, CollapseBlankLines>;
// Accepts "trim", "tabs:1" to "tabs:8", and "collapse-blank".// Throws std::invalid_argument for anything else.Cleanup parse_cleanup(std::string_view setting);
// The setting that parse_cleanup turns into this rule.std::string describe(const Cleanup& rule);
// Changes `document` as the rule says: trims every line, expands tabs in// every line, or collapses runs of blank lines.// Throws std::invalid_argument for an ExpandTabs width below 1.void apply(const Cleanup& rule, Document& document);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Turns one line of the settings file into a rule. Each `if` tries one// spelling and returns at once if it matches; returning a struct puts it// into the Cleanup variant. Anything that reaches the end matched nothing.Cleanup parse_cleanup(std::string_view setting) { if (setting == "trim") { return TrimTrailing{}; } if (setting == "collapse-blank") { return CollapseBlankLines{}; } constexpr std::string_view tabs = "tabs:"; if (setting.starts_with(tabs)) { // What follows "tabs:". substr on a string_view copies no text: it // is a smaller view into the same characters. For "tabs:2" it is "2". const std::string_view digits = setting.substr(tabs.size()); // Exactly one character, from '1' to '8'. So "tabs:0", "tabs:9", // "tabs:12", and "tabs:" are all refused. if (digits.size() == 1 && digits[0] >= '1' && digits[0] <= '8') { // The digit characters '0' to '9' have consecutive codes, so // subtracting '0' turns the character '2' into the number 2. return ExpandTabs{digits[0] - '0'}; } } throw std::invalid_argument{"unknown cleanup setting: " + std::string{setting}};}
// The reverse of parse_cleanup: the setting text for a rule, so// describe(parse_cleanup("tabs:2")) is "tabs:2" again. `overloaded`// (defined above this snippet) joins the three lambdas into one object,// and std::visit calls the one whose parameter type matches the rule the// variant holds. All three must return the same type, std::string; the// first and last spell it out with std::string{...}, because a bare// string literal would be a different type (const char*).std::string describe(const Cleanup& rule) { return std::visit(overloaded{ [](const TrimTrailing&) { return std::string{"trim"}; }, [](const ExpandTabs& tabs) { return "tabs:" + std::to_string(tabs.width); }, [](const CollapseBlankLines&) { return std::string{"collapse-blank"}; }, }, rule);}
// Runs the rule on the document. [&] lets each lambda use `document` by// reference, so the edits change the caller's document, not a copy.// The line rules go through edit_lines (the function template in// edit_lines.hpp): trim passes the function trim_trailing itself, and tabs// passes a lambda. Collapsing works on the whole list, so it is called// directly.void apply(const Cleanup& rule, Document& document) { std::visit(overloaded{ [&](const TrimTrailing&) { edit_lines(document, trim_trailing); }, [&](const ExpandTabs& tabs) { // parse_cleanup never makes a width below 1, but a // caller can write ExpandTabs{0} directly. // Checked first, so an empty document is refused too. if (tabs.width < 1) { throw std::invalid_argument{"apply: tab width must be at least 1"}; } // [width = tabs.width] copies the width into the // lambda under a new name; edit_lines calls it once // per line. edit_lines(document, [width = tabs.width](std::string& line) { expand_tabs(line, width); }); }, [&](const CollapseBlankLines&) { collapse_blank_lines(document.lines); }, }, rule);}How this code works: parse_cleanup, describe, and apply
parse_cleanup tries each spelling in turn and returns as soon as
one matches. Only the tab rule has a number in it, so it checks the
prefix tabs:, looks at what follows, and accepts exactly one digit
from 1 to 8. digits[0] - '0' turns that character into its number.
The match is exact, so a capital letter or an extra space is refused.
| Setting | Result |
|---|---|
trim |
a TrimTrailing |
tabs:2 |
an ExpandTabs with width 2 |
collapse-blank |
a CollapseBlankLines |
tabs:0 |
throws std::invalid_argument |
tabs:12 |
throws: two characters follow |
Trim |
throws: no spelling matches |
describe goes the other way. std::visit looks at which struct
the Cleanup holds and runs the matching lambda, so a rule parsed
from tabs:2 is described as tabs:2 again.
apply uses std::visit in the same way, but each lambda changes
the document, which it reaches through the [&] capture. Trimming and
tab expansion are per-line edits, handed to edit_lines; collapsing
blank lines must see neighbouring lines, so it works on the whole list.
The width check in the tab branch exists for a rule made directly in
code, such as ExpandTabs{0}, because parse_cleanup never produces
one.
The overloaded helper, which combines several lambdas into one
visitor, is explained on the
Visitor page. What changed:
- FR-2 is now easy.
describeturns a rule back into its setting, so the settings screen can list it; the tests check that every setting survives the round trip. Rules compare with==, so “istabs:2already on?” is one expression. - A rule is a value. It is copied into the hook that applies it,
[rule](Document& document) { apply(rule, document); }, so the hook owns its rule and nothing dangles. There is no heap allocation, and aCleanupis as large as its largest alternative, plus a tag and any padding. - The compiler checks completeness. Because
overloadedhas no catch-all case, adding a fourth struct toCleanupmakes everystd::visitthat does not handle it fail to compile, as long as no lambda takesautoand the new struct does not convert to a type already handled.
The cost is the reverse of that last point: the set is closed.
Another team cannot add a cleanup rule without editing cleanup.hpp,
and every function that visits a Cleanup changes when a rule is
added. That is right for a list of settings that one team owns, and
wrong for FR-3’s extensions, which is why the extensions stay
std::function hooks. The two tools meet in the usage below: each
parsed rule becomes a hook.
Tool 3: a function template for a fixed loop
Section titled “Tool 3: a function template for a fixed loop”LinePlugin was a Template Method whose fixed part is a loop. A
function template does the same job:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Calls edit on every line, in order. The edit is a template parameter, as// in std::for_each: it is used only during this call and never stored, so// there is no base class, no virtual call, and nothing to erase.// `template <std::invocable<std::string&> Edit>` means: Edit is whatever// type the caller passes (the compiler works it out), and it must be// callable with a std::string&. std::invocable is a C++20 concept; a call// with something else fails to compile, with a message naming it.// The compiler writes a separate copy of this function for each Edit type// it is used with. For a lambda, edit(line) is then a direct call that can// be inlined; a plain function, such as trim_trailing, arrives as a// function pointer.template <std::invocable<std::string&> Edit>void edit_lines(Document& document, Edit edit) { // `std::string&` (not const) is a reference to the line inside the // document, so the edit changes the line in place. for (std::string& line : document.lines) { edit(line); }}apply uses it with a plain function, edit_lines(document, trim_trailing), and with a lambda that captures the tab width. The
concept std::invocable<std::string&> states what an edit must
provide, and a call with something else fails at the call, with a
message that names the concept. The concept checks the call, not the
effect: an edit that takes std::string by value also satisfies it,
and silently changes nothing.
This is the form the standard library uses: the algorithms, such as
std::for_each and std::sort with a comparison, and std::erase_if
all take the varying step as a template parameter. It usually costs
nothing at run time: with a lambda, the compiler sees the edit’s type
and can inline it; a plain function is passed as a pointer and is
inlined only when the optimiser can see which function it is. It has
limits:
- It cannot be stored in a mixed list. Each lambda has its own
type, so
edit_lineswith two different lambdas is two different functions. That is fine for a step used during one call, and is why the hooks, which are stored, usestd::functioninstead. - It lives in a header, and each different edit is a separate instantiation, compiled where it is used.
A short rule: use a template parameter when the callable is used
during the call, and std::function when it must be kept. The
Template Method page’s
cost section
explains when a skeleton is worth a base class after all.
Tool 4: delegation instead of inheriting for reuse
Section titled “Tool 4: delegation instead of inheriting for reuse”SavedVersions needed a container’s storage, not its interface. So it
holds one, and forwards only what keeps the limit true:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The last few saved texts, oldest first. It holds a std::deque and offers// only the operations that keep the limit; it does not derive from the// container, so no caller can add past the limit or depend on the deque.// The invariant: size() is never more than limit_. Only add can grow the// deque, and it drops the oldest first when the deque is full, so the// invariant holds after every call. A std::deque removes from the front// cheaply, without shifting the rest as a std::vector would.class SavedVersions final {public: explicit SavedVersions(std::size_t limit); // throws std::invalid_argument for 0
// The text is taken by value and moved into the deque. void add(std::string text); // drops the oldest version when full std::size_t size() const { return versions_.size(); } // Forwards to the deque's at, which throws std::out_of_range for an // index of size() or more. The reference is to the stored text, so an // add that drops that version (the oldest, when full) leaves it dangling. const std::string& at(std::size_t index) const { return versions_.at(index); } // 0 is the oldest const std::string& latest() const; // throws std::out_of_range if nothing is saved
private: std::size_t limit_; std::deque<std::string> versions_;};There is no push_back to call, so the limit cannot be broken from
outside, and the after-version’s test checks that three adds keep two
versions. Forwarding takes a line per function, and that is the point:
each forwarded function is a decision that it keeps the invariant.
Because no caller can depend on the container, it could also change.
The before-version used a std::vector, which shifts every element
when it drops the oldest; the after-version uses a std::deque, which
drops from the front cheaply, and no caller had to change.
Public inheritance from a standard container has a second problem:
the containers have no virtual destructor, so deleting a
SavedVersions through a std::vector<std::string>* would be
undefined behaviour. Delegation avoids the question. The
Composition versus inheritance
lesson shows the same mistake with a std::deque, and a report
hierarchy refactored the same way.
The two extensions that were one class
Section titled “The two extensions that were one class”TrimAndCountPlugin needs no replacement. With hooks, trimming and
counting are two independent hooks, and a user can have either one,
both, or neither:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Declared before the editor, so they outlive the hooks that refer to them.// Local objects are destroyed in reverse order of declaration: of these// three, editor (with its hooks) goes first, then versions, then words.std::size_t words = 0;SavedVersions versions{2}; // keeps the last two saved textsEditor editor;
// The settings file names the cleanup rules; each becomes a value,// and each value becomes a hook that owns a copy of it.const std::vector<std::string> settings{"trim", "tabs:2", "collapse-blank"};std::string names;for (const std::string& setting : settings) { const Cleanup rule = parse_cleanup(setting); // throws for an unknown setting names += (names.empty() ? "" : ", ") + describe(rule); // "trim, tabs:2, ..." // [rule] copies the rule into the lambda, and the std::function // inside the editor keeps that copy. `rule` itself goes away at the // end of this pass of the loop; the hook's copy does not. editor.before_save([rule](Document& document) { apply(rule, document); });}
// Other extensions are plain lambdas that borrow what they update.// [&words] and [&versions] capture by reference: the hooks change the// variables above, not copies, which is why those must outlive editor.// The unused parameters have no names.editor.after_save([&words](const Document& document, const std::string&) { words = word_count(document); });editor.after_save([&versions](const Document&, const std::string& text) { versions.add(text); });
// A tab at the start, trailing spaces, two blank lines in a row (the// second holds only spaces), and a trailing tab.Document notes{"notes.txt", {"\tbuy milk ", "", " ", "call ana\t"}};// save takes a copy of notes; the hooks clean the copy, and notes// itself keeps its tab, as the output shows.const std::string saved = editor.save(notes);rules: trim, tabs:2, collapse-blanksaved: " buy milk\n\ncall ana\n"the open document still starts "\tbuy milk "words: 4after three saves, versions kept: 2oldest kept: " buy milk\n\ncall ana\npay rent\n"words: 8the class-based editor saves the same text: yesrefused: unknown cleanup setting: tabs:0How this code works: the first save, hook by hook
The editor has three before-save hooks, in the order of the settings,
and two after-save hooks. save copies notes and runs them on the
copy. Spaces are shown as · and tabs as →:
| After | Line 1 | Line 2 | Line 3 | Line 4 |
|---|---|---|---|---|
the copy of notes |
→buy·milk·· |
empty | ·· |
call·ana→ |
trim |
→buy·milk |
empty | empty | call·ana |
tabs:2 |
··buy·milk |
empty | empty | call·ana |
collapse-blank |
··buy·milk |
empty | (removed) | call·ana |
trimremoves the spaces and tabs at the end of each line. Line 3 had nothing else, so it becomes empty.tabs:2replaces the leading tab with spaces up to the next multiple of 2. It starts at column 0, so it adds one space, sees that 1 is not a multiple of 2, and adds a second.collapse-blankkeeps the first of two blank lines in a row and drops the second.
The three remaining lines are joined with a '\n' after each, giving
" buy milk\n\ncall ana\n". Then the after-save hooks run: the word
count sets words to 4 (buy, milk, call, ana), and versions stores
the text.
The program then adds “pay rent” and saves, then adds “water plants”
and saves. At the third save, versions already holds two texts, its
limit, so add drops the first save before storing the third. That
leaves the second save as the oldest, and words is 8 after the last
save.
Reading the output:
- The settings become three rules, and
describelists them back. - The saved text is trimmed, the leading tab is two spaces, and the
two blank lines became one. The open document still has its tab,
because
saveworks on a copy. - After three saves the editor kept two versions, the limit, and the oldest is the second save. The word count follows the last save.
- The class-based editor, given the same three rules as plug-in objects, writes the same text.
tabs:0is refused when the setting is parsed, before any hook exists.
Before and after
Section titled “Before and after”Text description of the diagram
Two diagrams. Before: EditorPlugin is a base class with empty virtual hooks. LinePlugin derives from it and holds the loop over lines, with a virtual edit_line. TrimPlugin and ExpandTabsPlugin derive from LinePlugin; CollapseBlankLinesPlugin derives from EditorPlugin directly. TrimAndCountPlugin derives from TrimPlugin. SavedVersions derives from std::vector of string. The Editor owns any number of EditorPlugin objects. After: the Editor owns any number of std::function hooks. A cleanup hook holds a copy of a Cleanup value, which is a std::variant of three structs, and applying it uses the edit_lines function template. The hook that records versions borrows a SavedVersions by reference, and SavedVersions owns one std::deque of string. There is no class hierarchy in the after-version.
Diagram source (Mermaid)
flowchart TB
subgraph Before
EP["EditorPlugin<br/>empty virtual hooks"]
LP["LinePlugin<br/>loop, virtual edit_line"] ==>|is a| EP
TP["TrimPlugin"] ==>|is a| LP
XP["ExpandTabsPlugin"] ==>|is a| LP
CP["CollapseBlankLinesPlugin"] ==>|is a| EP
TC["TrimAndCountPlugin"] ==>|is a| TP
SV["SavedVersions"] ==>|is a| VEC["std::vector of string"]
OE["Editor"] -->|"owns 0..*"| EP
end
subgraph After
ED["Editor"] -->|"owns 0..*"| FN["std::function hooks"]
FN -.->|"each holds a copy of"| CL["Cleanup<br/>std::variant of 3 structs"]
CL -.->|"applying it uses"| EL["edit_lines<br/>function template"]
FN -.->|"borrows, by reference"| SV2["SavedVersions"]
SV2 -->|"owns 1"| DQ["std::deque of string"]
endChoosing a tool
Section titled “Choosing a tool”| Tool | Good when | Poor when | Who owns what |
|---|---|---|---|
std::function |
the set is open, each case is one call, and cases are stored | a case needs several functions, a name, or removal; the callable is not copyable | the holder owns the callable and its by-value captures; by-reference captures are borrowed |
std::variant |
the set is closed and owned by one team; cases are data you compare, copy, or print | other code must add cases; alternatives differ greatly in size | the variant holds its alternative by value, with no heap |
| function template | the step is used during one call, and speed or simplicity matters | cases must be stored together, or chosen while the program runs | nothing is kept; the callable is a parameter |
| delegation | you want another class’s storage or work, not its interface | the class really is a kind of the other, and must be usable as one | the wrapper owns, or borrows, the object it forwards to |
| virtual interface | the set is open and each case is a role: several related functions, a name, its own data | a case is one function, or the set is closed | usually a std::unique_ptr to the base |
When inheritance is still the right choice
Section titled “When inheritance is still the right choice”Inheritance is not the problem; using it for the wrong job is. Keep a virtual interface when:
- The variant is a role, not a call. A
Shapethat hasdraw,bounds, andname, used together, is better as an interface than as threestd::functionmembers that could be set inconsistently. The Bridge page’sCanvasis one. - The cases need to be found, named, and documented. A class called
ExpressRateshows up in searches, stack traces, and reviews; a lambda inmaindoes not. - The boundary is a binary one. A plug-in loaded from a shared
library is usually reached through C functions or an abstract class
with a stable layout.
std::functionandstd::variantare library types whose layout can differ between standard library versions and implementations. Inside the program, the editor can still adapt such a plug-in into a hook. - A skeleton must never be skipped. When derived classes must not bypass a step, such as a check before every write, a non-virtual public function that calls private virtual steps enforces it, as Template Method shows. A function that takes callables enforces the skeleton only when it is used; whoever holds the callables can also call them directly and skip the check, whereas private virtual steps cannot be called from outside.
When the requirements change
Section titled “When the requirements change”- An extension can be disabled.
before_savereturns a handle that removes the hook when destroyed or cancelled. The Observer page shows one, including what happens when a hook removes itself duringsave. - A fourth cleanup rule,
wrap:N. Add a struct toCleanup. The compiler then refusesdescribeandapplyuntil they handle it, andparse_cleanupneeds one more branch, which no compiler can check, so a test should. - Other teams want their own cleanup rules. The set is no longer
closed, so a variant no longer fits. Those rules become ordinary
hooks, and only the built-in ones stay in
Cleanup. - Versions are kept on disk.
SavedVersionschanges inside, and no caller notices, because none of them could depend on the container.
Exercise
Section titled “Exercise”Exercise: Refactor a notifier hierarchy
An alerts service has grown this hierarchy. notify calls
should_send, and if it returns true, sends format(event) to every
recipient.
// The base class. notify is not virtual: it is the fixed skeleton (ask// should_send, then format the event and send it to each recipient). The// three protected virtual functions are the steps a derived class fills in.class Notifier {public: virtual ~Notifier() = default; void notify(const Event& event, const Recipients& recipients) const;protected: // A filter with a default: send everything unless a derived class says no. virtual bool should_send(const Event&) const { return true; } // Pure virtual (= 0): each channel must say how to word and deliver it. virtual std::string format(const Event& event) const = 0; virtual void send(const std::string& to, const std::string& text) const = 0;};// The derived classes. The comment inside each says which functions it// overrides.class EmailNotifier : public Notifier { /* format, send */ };class QuietHoursEmailNotifier : public EmailNotifier { /* should_send: not 22:00-07:00 */ };class SmsNotifier : public Notifier { /* format: at most 160 characters; send */ };class QuietHoursSmsNotifier : public SmsNotifier { /* should_send: not 22:00-07:00 */ };class UrgentOnlySmsNotifier : public SmsNotifier { /* should_send: urgent events only */ };// The addresses to send to. all_valid reports whether every one is valid.class Recipients : public std::vector<std::string> {public: bool all_valid() const;};Users choose a channel, and tick “quiet hours” and “urgent only”, which can be combined. Another team will add a push-notification channel next month, and product managers keep asking for new filters, such as “only during a user’s working hours”.
- For each class, say what its use of inheritance is for, using the table in Step 1.
- Choose a replacement for each, or say why the inheritance should stay.
- Say who owns what in your design.
Show the explained answer
1 and 2, class by class.
Notifier,EmailNotifier, andSmsNotifier: keep an interface, but only for the channel. A channel is a role with two related functions,formatandsend, and the set of channels is open: another team is adding push. That is what a virtual interface is for. Astd::variantwould force that team to edit the variant. What should change is that the filter is no longer part of the channel: make aChannelinterface withformatandsend, and nothing else.- The quiet-hours and urgent-only subclasses: hooks, not classes.
They exist to combine “a channel” with “a filter”, which is the
TrimAndCountPluginproblem again, andQuietHoursSmsNotifierrepeatsQuietHoursEmailNotifier’s rule. A filter is one call, “should this event be sent?”, and new ones keep arriving, so store them asstd::function<bool(const Event&)>in a list, and send only if every filter agrees. “Quiet hours” and “urgent only” can then be used with any channel, together or alone. If the filters were a fixed list of settings that must be shown back to the user, astd::variantof filter structs would fit better, for the same reasons asCleanup; with new filters arriving often, it would not. notify’s loop: a plain function. Once the filter and the channel are separate, “if every filter agrees, format once and send to each recipient” is a short function that takes the filters and the channel. It needs no base class.Recipients: delegation, or nothing. It derives fromstd::vectoronly to addall_valid. A free function,bool all_valid(const std::vector<std::string>& recipients), does that without a new type. If the list must keep an invariant, for example every address is valid, make it a class that holds the vector, checks each address inadd, and offers no other way in, likeSavedVersions.
3. Ownership. The code that reads the user’s choices creates the
channel and owns it as a std::unique_ptr<Channel>, and builds the
list of filters, which owns its callables. A filter that needs the
clock or the user’s time zone captures it by value, or borrows an
object that the service owns and that outlives the list. notify
borrows the channel, the filters, and the recipients for the call and
keeps none of them. Five subclasses become one interface with two
implementations, a list of small functions, and two free functions,
and the push team adds one class.
With a public Channel::send and a free notify, any code can send
without the filters. If no message may ever bypass them, wrap them in
a small Notifier class that owns the std::unique_ptr<Channel> and
the filter list, and make notify its only public function. That is
still composition, not a hierarchy.