Skip to content

Composition versus inheritance

Difficulty: Intermediate

Key concepts

  • composition
  • inheritance
  • is-a
  • has-a
  • delegation
  • fragile base class
  • class explosion
  • substitutability
  • How to tell an “is a” relationship from a “has a” relationship.
  • Why inheriting from a class only to reuse its code is a warning sign.
  • How to build a class from members and delegate work to them.
  • When inheritance is still the right tool.

The previous lesson used inheritance for one purpose: several classes implement one interface, so code can use any of them through a Notifier&. Inheritance is also tempting for a second purpose: reusing code. If class B needs what class A already does, deriving B from A gives it all of A’s members for free.

Composition is the other way to reuse a class: B has an A as a member and calls it when it needs it. The two read differently:

  • Inheritance says “is a”. A SmsNotifier is a Notifier: anywhere a Notifier is expected, a SmsNotifier works, and keeps the Notifier’s contract.
  • Composition says “has a”. A Library has a Catalog. A Library is not a kind of catalog, and nothing that expects a Catalog should be handed a Library.

Code reuse alone does not make something “is a”. This lesson follows a design that inherited for reuse, finds where it hurts, and rebuilds it with composition.

A library prints reports of its loans. The first report listed overdue loans as CSV. Then someone needed the same list as an HTML table, and the natural move was to put the shared loop in a base class and let subclasses fill in the format:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan.hpp
// CPP-11 example: the data both report designs work on.
//
// Ownership: plain value type. Thread safety: safe to share read-only.
#pragma once
#include <string>
namespace lld::composition {
// One loan as the reports see it: a book's title and how late it is. A plain
// struct, because any title and any number of days is acceptable: there is
// no rule to protect, so the members are simply public.
struct Loan {
std::string title;
int days_overdue = 0; // 0 if not overdue
};
} // namespace lld::composition

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
// The base class every report derives from. It owns the loans and the loop
// that turns them into text (render), and leaves four steps to subclasses:
// include (which loans), begin, row, and end (how they are written). Only
// row has no default, so the class is abstract.
class OverdueReport {
public:
// Takes the loans by value and moves them into loans_, so the report
// keeps its own copy and the caller can still std::move a vector in to
// avoid copying it.
explicit OverdueReport(std::vector<Loan> loans) : loans_(std::move(loans)) {}
virtual ~OverdueReport() = default;
// The reused part: subclasses customize the steps below.
// Each call to begin, include, row, and end is virtual, so it runs the
// subclass's version if there is one. Example: a CsvOverdueReport with
// one loan {"Emma", 3} returns "title,days_overdue\nEmma,3\n".
[[nodiscard]] std::string render() const {
std::string out = begin();
for (const Loan& loan : loans_) {
if (include(loan)) out += row(loan); // += appends to out
}
return out + end();
}
protected:
// The steps. Protected: subclasses may override them, outside code
// cannot call them. A subclass must know that render calls begin once,
// then row only for loans that include accepts, then end once; nothing
// in these signatures says so.
// By default only loans more than 0 days late are included.
[[nodiscard]] virtual bool include(const Loan& loan) const { return loan.days_overdue > 0; }
[[nodiscard]] virtual std::string begin() const { return ""; }
[[nodiscard]] virtual std::string row(const Loan& loan) const = 0;
[[nodiscard]] virtual std::string end() const { return ""; }
// Copies and moves are protected, as for Notifier in the previous
// lesson, so a report cannot be sliced into an OverdueReport.
OverdueReport(const OverdueReport&) = default;
OverdueReport& operator=(const OverdueReport&) = default;
OverdueReport(OverdueReport&&) = default;
OverdueReport& operator=(OverdueReport&&) = default;
private:
std::vector<Loan> loans_;
};
// Overdue loans as CSV: a header line, then "title,days" per loan.
class CsvOverdueReport : public OverdueReport {
public:
// Inherits the base constructor, so CsvOverdueReport(loans) works
// without writing it again.
using OverdueReport::OverdueReport;
protected:
std::string begin() const override { return "title,days_overdue\n"; }
// std::to_string turns the int into text, such as 3 into "3".
std::string row(const Loan& loan) const override {
return loan.title + ',' + std::to_string(loan.days_overdue) + '\n';
}
};
// Overdue loans as an HTML table: one <tr> row per loan.
class HtmlOverdueReport : public OverdueReport {
public:
using OverdueReport::OverdueReport;
protected:
std::string begin() const override { return "<table>\n"; }
std::string row(const Loan& loan) const override {
return " <tr><td>" + loan.title + "</td><td>" + std::to_string(loan.days_overdue) +
"</td></tr>\n";
}
std::string end() const override { return "</table>\n"; }
};
// A later request, "all loans as CSV", reused CsvOverdueReport by deriving
// from it again. An "all loans as HTML" report would need a fourth class.
class CsvAllLoansReport : public CsvOverdueReport {
public:
using CsvOverdueReport::CsvOverdueReport;
protected:
// Overrides only the selection: every loan, overdue or not. It inherits
// CSV's begin and row, and the base's empty end.
bool include(const Loan&) const override { return true; }
};
How this code works: CsvAllLoansReport::render

render is written once, in OverdueReport, but each step it calls is virtual, so the version that runs depends on the real object. For a CsvAllLoansReport, the four steps come from three different classes:

Step render calls Version that runs Why
begin() CsvOverdueReport::begin the parent overrides it
include(loan) CsvAllLoansReport::include the class itself overrides it: always true
row(loan) CsvOverdueReport::row the parent overrides it
end() OverdueReport::end nobody overrides it: the default ""

With the loans {"Middlemarch", 3}, {"Emma", 0}, {"Ivanhoe", 12}, it returns the header line title,days_overdue and then all three rows, including Emma,0, which is not overdue at all.

To know what one report prints, a reader has to look at three classes and know the order in which render calls the steps. That hidden knowledge is what the next section calls the fragile base class.

OverdueReport::render is the reused part. It calls protected virtual functions (begin, row, end, include) that subclasses override. This shape has a name, the Template Method pattern, and it is sometimes the right one. Here it mixes two unrelated choices in one hierarchy:

  • The format (CSV or HTML), and
  • the selection (overdue loans, or all loans).

Each subclass fixes both. So when a request for “all loans as CSV” arrived, the only way to reuse the CSV format was to derive from CsvOverdueReport and override include. Now look at what that design costs.

Before, as an entity sketch: one class per combination of format and selection
Text description of the diagram

Five boxes. Thick “is a” arrows go from CsvOverdueReport and from HtmlOverdueReport up to OverdueReport, an abstract base class, and from CsvAllLoansReport up to CsvOverdueReport, a second level. A solid arrow labelled “owns 0..*” goes from OverdueReport to Loan: the base class holds the loans. Format and selection are both fixed by which class you pick.

Diagram source (Mermaid)
flowchart BT
CsvOverdueReport ==>|is a| OverdueReport["OverdueReport (abstract)"]
HtmlOverdueReport ==>|is a| OverdueReport
CsvAllLoansReport ==>|is a| CsvOverdueReport
OverdueReport -->|"owns 0..*"| Loan

class OverdueReport

abstract base: render() calls the virtual steps in order

Data members

  • std::vector<Loan> loans_;

Member functions

  • explicit OverdueReport(std::vector<Loan> loans);
  • std::string render() const;
  • virtual bool include(const Loan& loan) const; protected; default: overdue only
  • virtual std::string begin() const; protected; default: ""
  • virtual std::string row(const Loan& loan) const = 0; protected
  • virtual std::string end() const; protected; default: ""

class CsvOverdueReport

is an OverdueReport

Member functions

  • std::string begin() const override;
  • std::string row(const Loan& loan) const override;

class HtmlOverdueReport

is an OverdueReport

Member functions

  • std::string begin() const override;
  • std::string row(const Loan& loan) const override;
  • std::string end() const override;

class CsvAllLoansReport

is a CsvOverdueReport

Member functions

  • bool include(const Loan& loan) const override; always true
Before, as a class outline: the base class owns the loans and the algorithm; each subclass overrides some protected steps
  • Class explosion. Two formats and two selections need four concrete classes, one per combination; three formats and three selections need nine. Every new combination is a new class, and “all loans as HTML” does not exist until someone writes it.
  • The names lie. CsvAllLoansReport is an OverdueReport and a CsvOverdueReport, according to the type system, yet it does not report overdue loans. Code that accepts an OverdueReport& and assumes every row is overdue is wrong for it. The hierarchy no longer describes substitutable types.
  • Fragile base class. Each subclass is tightly coupled to the base: it depends on how render uses the protected steps: their order, how often each is called, and that row is only called for included loans. None of that is in a function signature. If OverdueReport::render is later changed, for example to call row for a total line, every subclass is affected, including ones in other teams’ code that the base class’s author has never seen.
  • Each choice is a type. Choosing a format and a selection means choosing a class, when the code is written, so a user’s choice of format must be turned into a choice of class with a switch somewhere.
  • Testing a format means testing a whole report. There is no way to test the CSV row format without also building a report and its loop.

The fix: a report that has a formatter and a filter

Section titled “The fix: a report that has a formatter and a filter”

Separate the two choices, give each its own type, and let the report have one of each:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

after.hpp
// Interface: how one report is written. Stateless. A report calls begin()
// once, then row() once per included loan, then end() once.
// It knows nothing about which loans are chosen: that is the filter's job.
// Built like Notifier in the previous lesson: pure virtual functions, a
// virtual destructor, and protected copies and moves so it cannot be sliced.
class Formatter {
public:
virtual ~Formatter() = default;
[[nodiscard]] virtual std::string begin() const = 0;
[[nodiscard]] virtual std::string row(const Loan& loan) const = 0;
[[nodiscard]] virtual std::string end() const = 0;
protected:
Formatter() = default;
Formatter(const Formatter&) = default;
Formatter& operator=(const Formatter&) = default;
Formatter(Formatter&&) = default;
Formatter& operator=(Formatter&&) = default;
};
// The two formats. Each only declares the three steps here; the bodies are
// in after.cpp. Example rows: CSV writes "Emma,3", HTML writes
// " <tr><td>Emma</td><td>3</td></tr>". final: nothing derives from them.
class CsvFormatter final : public Formatter {
public:
std::string begin() const override;
std::string row(const Loan& loan) const override;
std::string end() const override;
};
class HtmlFormatter final : public Formatter {
public:
std::string begin() const override;
std::string row(const Loan& loan) const override;
std::string end() const override;
};

Formatter is an interface in the sense of the previous lesson: pure virtual functions, a public virtual destructor, and protected copy operations so it cannot be sliced. It knows how to write a report, and nothing about which loans belong in it.

The selection does not need a class hierarchy at all. A filter is “a function from a loan to bool”, which std::function<bool(const Loan&)> expresses directly. It can hold a plain function such as is_overdue, or a lambda.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

after.hpp
// Which loans a report includes.
// `using X = ...;` gives a type a shorter name. std::function<bool(const
// Loan&)> is a box that can hold any callable (a plain function, a lambda)
// that takes a const Loan& and returns bool. A default-made one is empty
// and holds nothing.
using LoanFilter = std::function<bool(const Loan&)>;
// Two ready-made filters. is_overdue: more than 0 days late. any_loan:
// always true, so every loan is included.
[[nodiscard]] bool is_overdue(const Loan& loan);
[[nodiscard]] bool any_loan(const Loan& loan);
// A report made of two parts it owns: a Formatter (how to write) and a
// LoanFilter (what to include). It has no virtual functions and no base
// class; changing the format or the selection means passing different parts,
// not writing a new class.
// Invariant: formatter_ is not null and filter_ is not empty, except in a
// Report that has been moved from, which may only be destroyed or assigned to.
class Report {
public:
// Takes ownership of the formatter (pass it with std::make_unique or
// std::move) and keeps the filter by value.
// Throws std::invalid_argument if formatter is null or filter is empty.
Report(std::unique_ptr<const Formatter> formatter, LoanFilter filter);
// Writes the loans the filter accepts, in the order given, in the
// formatter's format. Reads the caller's vector; does not keep it.
[[nodiscard]] std::string render(const std::vector<Loan>& loans) const;
private:
// `const Formatter`: the report may only call const functions on it.
std::unique_ptr<const Formatter> formatter_; // has-a: owned, delegated to
LoanFilter filter_; // has-a: owned by value
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

after.cpp
// The member initializer list (after the colon) moves each parameter into
// its member: the formatter's ownership passes to formatter_, and the filter
// is moved rather than copied. The checks then look at the members, because
// the parameters have just been moved from. If a check throws, no Report is
// created, and the members already built are destroyed automatically, so
// the formatter is not leaked.
Report::Report(std::unique_ptr<const Formatter> formatter, LoanFilter filter)
: formatter_(std::move(formatter)), filter_(std::move(filter)) {
if (formatter_ == nullptr) throw std::invalid_argument("a report needs a formatter");
// An empty std::function converts to false, so !filter_ means "holds no
// callable"; calling an empty one would throw std::bad_function_call.
if (!filter_) throw std::invalid_argument("a report needs a filter");
}
// The same loop as OverdueReport::render, but each decision goes to a member
// instead of a virtual function of this class.
std::string Report::render(const std::vector<Loan>& loans) const {
std::string out = formatter_->begin(); // delegate: Report decides the
for (const Loan& loan : loans) { // structure, the formatter the format
// filter_(loan) calls whatever callable the filter holds, for example
// is_overdue, and gets back true or false.
if (filter_(loan)) out += formatter_->row(loan);
}
return out + formatter_->end();
}
How this code works: Report::render

Take the report overdue_csv from main below: a CsvFormatter and the filter is_overdue, rendering the loans Middlemarch (3 days), Emma (0), and Ivanhoe (12).

Step Call Result out ends with
before the loop formatter_->begin() "title,days_overdue\n" the header line
loan 1, Middlemarch filter_(loan), then row true, "Middlemarch,3\n" Middlemarch,3
loan 2, Emma filter_(loan) false: row not called still Middlemarch,3
loan 3, Ivanhoe filter_(loan), then row true, "Ivanhoe,12\n" Ivanhoe,12
after the loop formatter_->end() "" for CSV unchanged

The loop is the same as in OverdueReport::render. The difference is where each answer comes from: “include this loan?” goes to the filter member, and “how is it written?” goes to the formatter member. Report never needs to know which formatter or which filter it was given, and swapping either one is a constructor argument, not a new class.

Report is built from its parts:

  • It owns its formatter through std::unique_ptr<const Formatter>, because formatters are polymorphic and the report is their only owner. const, because the report only reads from it.
  • It owns its filter by value. std::function is a copyable value type. It can hold only callables that can themselves be copied, so a lambda that captures a std::unique_ptr will not compile into one (C++23 adds std::move_only_function for that). Report as a whole is still move-only, because of its std::unique_ptr member.
  • It delegates. render keeps the one thing that is really shared, the loop over the loans, and forwards each decision to a member: “is this loan included?” to the filter, “how is it written?” to the formatter. This is delegation: the member does the work, through its public interface, and the report does not need to know which formatter or filter it has.
  • Its invariant is that both parts are present, and the constructor enforces it, so render never checks for null. Report declares no special members (the Rule of Zero), so it can be moved; a moved-from Report has lost its parts and, like the handles in earlier lessons, may only be destroyed or assigned to. The header says so.

Notice what the formatter does not see: the loop, the filter, or any protected state of the report. It has a three-function public contract and nothing else, so Report::render can change freely as long as it keeps calling begin, row, and end in that order, which is what Formatter’s header comment promises.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Three loans, each {title, days_overdue}. Emma is not overdue.
const std::vector<Loan> loans{{"Middlemarch", 3}, {"Emma", 0}, {"Ivanhoe", 12}};
// Each report is built from a formatter and a filter. make_unique creates
// the formatter and hands its ownership to the report. Passing the name
// is_overdue (no brackets) passes the function itself, which the
// LoanFilter parameter stores.
const Report overdue_csv(std::make_unique<CsvFormatter>(), is_overdue);
const Report all_html(std::make_unique<HtmlFormatter>(), any_loan);
// A filter needs no named function: here, loans more than a week overdue.
// The lambda captures nothing (empty []), takes a loan, returns a bool.
const Report long_overdue_csv(std::make_unique<CsvFormatter>(),
[](const Loan& loan) { return loan.days_overdue > 7; });
// Expected: CSV with Middlemarch and Ivanhoe; an HTML table with all
// three; CSV with only Ivanhoe (12 > 7).
std::cout << overdue_csv.render(loans) << '\n'
<< all_html.render(loans) << '\n'
<< long_overdue_csv.render(loans);
Expected output
title,days_overdue
Middlemarch,3
Ivanhoe,12
<table>
<tr><td>Middlemarch</td><td>3</td></tr>
<tr><td>Emma</td><td>0</td></tr>
<tr><td>Ivanhoe</td><td>12</td></tr>
</table>
title,days_overdue
Ivanhoe,12

Two formatters and any number of filters combine freely. “All loans as HTML” needed no new class, and a one-off filter is a lambda at the point of use.

After, as an entity sketch: a Report owns one formatter and one filter, and delegates to both
Text description of the diagram

Six boxes. Solid arrows go from Report to Formatter, an interface, labelled “owns 1, unique_ptr; delegates to”, and to LoanFilter, a std::function, labelled “owns 1, by value; delegates to”. A dashed arrow labelled “uses, during render” goes from Report to Loan: the loans are a parameter of render, not stored. Thick “implements” arrows go from CsvFormatter and HtmlFormatter to Formatter. There is one level of inheritance, between the interface and its implementations; the report itself inherits from nothing.

Diagram source (Mermaid)
flowchart LR
Report -->|"owns 1, unique_ptr; delegates to"| Formatter["Formatter (interface)"]
Report -->|"owns 1, by value; delegates to"| LoanFilter["LoanFilter (std::function)"]
Report -.->|"uses, during render"| Loan
CsvFormatter ==>|implements| Formatter
HtmlFormatter ==>|implements| Formatter

class Report

composes a format and a selection

Data members

  • std::unique_ptr<const Formatter> formatter_; owned; never null except after a move
  • LoanFilter filter_; std::function<bool(const Loan&)>, owned by value

Member functions

  • Report(std::unique_ptr<const Formatter> formatter, LoanFilter filter); throws if formatter is null or filter is empty
  • std::string render(const std::vector<Loan>& loans) const;

interface (abstract class) Formatter

implemented by the final classes CsvFormatter and HtmlFormatter

Member functions

  • virtual std::string begin() const = 0;
  • virtual std::string row(const Loan& loan) const = 0;
  • virtual std::string end() const = 0;
After, as a class outline: the report has no virtual functions; the variation is in the parts it owns

Restructuring a design should not change what it does. The tests render the same loans through the old hierarchy and the new composition and require identical output, then check what only the new design can do:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_reports.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(actual, expected) records one if
// the two differ and prints both; 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. `loans` is the same three loans
// as in main: Middlemarch 3, Emma 0, Ivanhoe 12 days overdue.
// The refactoring check: for each report the old hierarchy could make, the
// new design, given the matching formatter and filter, must produce exactly
// the same string, character for character.
LLD_TEST(composed_reports_match_the_old_hierarchy) {
// A namespace alias: old:: is a short name for lld::composition::before.
namespace old = lld::composition::before;
LLD_CHECK_EQ(Report(std::make_unique<CsvFormatter>(), is_overdue).render(loans),
old::CsvOverdueReport(loans).render());
LLD_CHECK_EQ(Report(std::make_unique<HtmlFormatter>(), is_overdue).render(loans),
old::HtmlOverdueReport(loans).render());
LLD_CHECK_EQ(Report(std::make_unique<CsvFormatter>(), any_loan).render(loans),
old::CsvAllLoansReport(loans).render());
}
// "All loans as HTML" had no class in the old design. Here it is one line;
// Emma (0 days) appearing proves the any_loan filter was used.
LLD_TEST(a_new_combination_needs_no_new_class) {
const std::string html_all = Report(std::make_unique<HtmlFormatter>(), any_loan).render(loans);
LLD_CHECK(html_all.find("<td>Emma</td>") != std::string::npos);
}
// The constructor enforces the invariant: a null formatter, or a nullptr
// filter (which makes an empty std::function), throws.
LLD_TEST(a_report_rejects_missing_parts) {
LLD_CHECK_THROWS(Report(nullptr, is_overdue), std::invalid_argument);
LLD_CHECK_THROWS(Report(std::make_unique<CsvFormatter>(), nullptr), std::invalid_argument);
}

Keeping the old classes alive in a test like this is a useful technique while migrating callers: it pins the behaviour down until the last caller has moved, after which the old classes and the comparison test can be deleted.

The after design still uses inheritance, between Formatter and its implementations. That is the use the previous lesson recommended: an interface with several interchangeable implementations, where every implementation really is a Formatter and keeps its contract. What disappeared is inheritance used to reuse a base class’s implementation.

A useful test before writing class B : public A is the substitution question: would every piece of code that works with an A& still be correct if given a B?

  • CsvFormatter for Formatter: yes. Any code that writes a report through a Formatter& works with it.
  • CsvAllLoansReport for OverdueReport: no. Code that expects overdue loans is wrong for it.
  • A Stack derived from std::vector<int>, to reuse its storage: no. A std::vector<int>& allows insert in the middle, which breaks the stack’s only rule. (The standard containers are also not designed as base classes: they have no virtual destructor.)

If the answer is no, the relationship is “has a” or “is implemented using”, and the class should hold the other as a member. The principles section returns to this question as the Liskov Substitution Principle.

Use public inheritance when:

  • There is an interface with several implementations, chosen at run time, as with Formatter or the previous lesson’s Notifier;
  • every derived class passes the substitution question, and
  • the hierarchy is shallow: usually an interface and one level of implementations.

Inheriting an implementation, as Template Method does, is reasonable when the base class is designed for it: its documentation says exactly which steps are called, in what order, and what each override may assume, and there is only one dimension of variation. When a second independent choice appears, as the selection did here, move to composition.

Use composition when:

  • you want to reuse a class’s behaviour but your class is not a kind of it;
  • there are several independent choices (format, selection, destination), which would multiply into classes;
  • the choice should be made or changed at run time, from configuration or user input;
  • you want to test the parts separately. Each formatter can be tested with no report and no loans list.
  • Inheriting to get access to a few helper functions. Make them free functions or put them in a member.
  • Deriving from a standard container to reuse its storage. Hold it as a member and expose only the operations your class’s rules allow.
  • One hierarchy for two independent choices. Each extra choice multiplies the number of classes. Split the choices into separate members.
  • Deep hierarchies, where a class overrides a function of its grandparent and depends on what its parent does in between.
  • Replacing every hierarchy with composition. An interface with real implementations is inheritance used well. The goal is to stop inheriting implementation for reuse, not to stop using virtual functions.

New requirement: “Reports must also be sent by email, not only returned as a string.”

In the before design, the destination would be a third choice baked into each class: EmailedCsvOverdueReport, and so on, doubling the class count. In the composed design, it is a separate concern, and it does not even belong inside Report: render returns a string, and the code that asked for the report passes that string to whatever sends it, for example a Notifier from the previous lesson. Report keeps one job: turning loans into text. If a sender must be chosen per report, a ReportJob can hold a Report and a Notifier&, one more composition, with no change to Report, Formatter, or any existing formatter.

Exercise: Redesign a fragile hierarchy

A reading-list feature needs a list that holds at most a fixed number of titles, dropping the oldest when full. It was written like this:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

// A list of recent titles that keeps at most `limit` of them.
// It inherits from std::deque, a container that can add and remove at both
// ends quickly.
class RecentTitles : public std::deque<std::string> {
public:
explicit RecentTitles(std::size_t limit) : limit_(limit) {}
// Adds a title at the back; if that makes one too many, drops the
// oldest from the front. push_back, size, and pop_front are the
// inherited std::deque functions.
void add(std::string title) {
push_back(std::move(title));
if (size() > limit_) pop_front();
}
private:
std::size_t limit_;
};
class LoggedRecentTitles : public RecentTitles {
public:
using RecentTitles::RecentTitles; // reuse RecentTitles' constructor
// Logs the title to std::clog (the standard log stream), then calls the
// base class's add by name to do the real work.
void add(std::string title) {
std::clog << "added " << title << '\n';
RecentTitles::add(std::move(title));
}
};
  1. Name at least three ways code that uses these classes can break the rule “at most limit titles” or skip the logging.
  2. Redesign RecentTitles with composition, keeping add, size, and read access to the titles.
  3. How would you add logging without LoggedRecentTitles?
Show the explained answer
  1. Ways to break it:

    • The whole std::deque interface is public. titles.push_back(...), insert, resize, or emplace_front add titles without checking the limit. The class’s rule holds only if every caller remembers to use add.
    • add is not virtual. Through a RecentTitles&, a LoggedRecentTitles runs the base add, and nothing is logged. Making it virtual would not help with the first problem, and std::deque<std::string>& reaches the deque’s own functions anyway.
    • Conversion to the base. A RecentTitles can be passed to any function taking std::deque<std::string>&, which may change it freely, and copied into a std::deque<std::string> value, slicing off the limit.
    • Deleting through the base. std::deque has no virtual destructor, so owning a RecentTitles through a std::unique_ptr<std::deque<std::string>> has undefined behaviour.
  2. Hold the deque as a private member and expose only what the rule allows:

IllustrativeA fragment for explanation; not compiled on its own.

// Invariant: titles_.size() <= limit_, and limit_ > 0.
class RecentTitles {
public:
// A limit of 0 could never hold a title, so it is refused at once.
explicit RecentTitles(std::size_t limit) : limit_(limit) {
if (limit_ == 0) throw std::invalid_argument("limit must be positive");
}
// The only function that changes titles_, so the limit is checked in
// exactly one place: add at the back, then drop the oldest if too many.
void add(std::string title) {
titles_.push_back(std::move(title));
if (titles_.size() > limit_) titles_.pop_front();
}
[[nodiscard]] std::size_t size() const noexcept { return titles_.size(); }
// Read-only access: a const reference lets callers look at the titles
// without copying them, but not change them.
[[nodiscard]] const std::deque<std::string>& titles() const noexcept { return titles_; }
private:
std::size_t limit_;
std::deque<std::string> titles_; // has-a: a member, not a base class
};

add is now the only way to change the titles, so the invariant is enforced in one place. Callers read through a const reference, which cannot modify them. (Returning the deque also exposes that the storage is a deque; returning a std::vector<std::string> copy, or offering begin()/end(), would hide that, at some cost.) The class follows the Rule of Zero, and is copyable and movable with its rule intact.

  1. Logging is a second, independent concern, so it should not be a subclass. Options, from simplest:
    • Log at the call site that calls add, if there is only one.
    • Give RecentTitles an optional observer, such as a std::function<void(const std::string&)> on_added member called by add. Logging is then one lambda, and other reactions (updating a display) need no new class.
    • If several kinds of list must be logged the same way, define a small interface for “something you can add a title to”, and a logging wrapper that implements it and forwards to another one: the Decorator pattern, covered in the patterns section.
  • Inheritance says “is a” and is right when every derived class can stand in for the base; composition says “has a” and is the default for reuse.
  • Inheriting only to reuse code couples a class to its base’s implementation, makes independent choices multiply into classes, and lets names stop matching behaviour.
  • Composition builds a class from members and delegates work to them through their public interfaces, so the parts can be chosen at run time and tested alone.
  • Interfaces with several implementations are still inheritance used well. Keep hierarchies shallow, and ask the substitution question before deriving.