Skip to content

The Liskov Substitution Principle

Difficulty: Intermediate

Key concepts

  • Liskov substitution principle
  • substitutability
  • contracts
  • preconditions and postconditions
  • invariants
  • redesigning a hierarchy
  • What the Liskov Substitution Principle (LSP) says, and why “is a” in plain English is not enough to justify public inheritance.
  • How to write down a class’s contract (preconditions, postconditions, invariants) and check a derived class against it, line by line.
  • The classic violations: an override that throws “not supported”, an override that quietly does nothing, and the square that is not a rectangle.
  • How to fix a violation by redesigning the hierarchy, so the compiler rejects the wrong use, instead of adding run-time type checks.
  • How to test substitutability with one contract test run against every implementation.

A music app lets listeners keep playlists.

  1. FR-1 A listener can create a named playlist, add songs to the end, and remove songs.
  2. FR-2 Each week the app publishes a chart: the most-played songs, most played first. Listeners can read a chart and copy songs from it into their own playlists, but cannot edit it.
  3. FR-3 “Add missing songs”: copy every song from one list into a playlist, skipping titles the playlist already has.

A developer reasoned: “A chart is a playlist that listeners cannot edit.” So Chart derives from Playlist, and its editing functions are overridden to refuse. The program compiled. A week later, a crash report: “add missing songs” had been called with a chart as the destination, and threw an exception nobody caught.

The Liskov Substitution Principle says:

Code that works with a base type must keep working, unchanged, when it is given any derived type.

“Working” means “doing what the base type promised”. So the principle is really about promises. Every class has a contract, written down or not, made of three parts. A derived class must keep each part:

Part of the contract What it says A derived class may… A derived class must not…
Precondition What must be true before a call ask for the same, or less ask for more (“only if the user is logged in”, “only if editable”)
Postcondition What is true after a call, including which errors it may report promise the same, or more promise less (do nothing, throw a new kind of error, return a value outside the promised range)
Invariant What is always true of an object between calls add invariants of its own break one of the base class’s

LSP is the “L” in SOLID.

Why does it matter? Because the point of a base class is that callers do not need to know which derived class they have. A function that takes a Playlist& was written, reviewed, and tested against Playlist’s contract. If some derived class does not keep that contract, every such function is now wrong for it, and nothing in the function’s code shows it.

Step 1: write down the base class’s contract

Section titled “Step 1: write down the base class’s contract”

Here is the “before” design. Read the comments: they are Playlist’s contract.

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

before.hpp
// The "before" design. Playlist itself is fine: a list of songs the
// listener can edit. The flaw is Chart, below. Playlist's editing
// functions are `virtual`, so a derived class may replace them, and code
// written against Playlist& calls whichever version the real object has.
class Playlist {
public:
// `explicit` stops a plain std::string being silently turned into a
// Playlist. Throws std::invalid_argument if the name is empty.
explicit Playlist(std::string name); // throws if the name is empty
// A virtual destructor, so deleting a derived object through a
// Playlist pointer runs the derived class's clean-up too.
virtual ~Playlist() = default;
// These comments are the contract: what every caller may rely on.
// Postcondition: size() is one larger and at(size() - 1) is `song`.
// Throws std::invalid_argument for a song check_song refuses.
virtual void add(Song song);
// Throws std::out_of_range if there is no entry at `index`.
virtual void remove_at(std::size_t index);
const std::string& name() const { return name_; }
std::size_t size() const { return songs_.size(); }
// std::vector::at checks the index and throws std::out_of_range when
// it is too big, so a bad index can never read past the end.
const Song& at(std::size_t index) const { return songs_.at(index); }
protected:
// Copying is allowed only from inside the hierarchy (protected), which
// stops "slicing": copying a Chart into a plain Playlist by accident.
Playlist(const Playlist&) = default;
Playlist& operator=(const Playlist&) = default;
private:
std::string name_;
std::vector<Song> songs_; // the songs, in playing order, owned by value
};
// This week's most-played songs. Listeners must not edit it, so the
// editing functions are overridden to refuse. THE FLAW: Chart says it is a
// Playlist (public inheritance), yet it breaks every editing promise
// above. Code that accepts a Playlist& compiles with a Chart and then
// fails at run time. `final` means nothing may derive from Chart.
class Chart final : public Playlist {
public:
Chart(std::string name, const std::vector<Song>& songs);
void add(Song song) override; // always throws std::logic_error
void remove_at(std::size_t index) override; // always throws std::logic_error
};
// Written against Playlist: adds each song whose title is not already in
// the playlist, and returns how many it added. Correct for a real
// Playlist; given a Chart, the first song it tries to add throws
// std::logic_error, an exception add's contract never mentions.
std::size_t add_missing(Playlist& playlist, const std::vector<Song>& songs);

Now check Chart against each line of Playlist’s contract:

Playlist promises Does Chart keep it?
add(song): afterwards, size() is one larger and the last song is song No. It throws std::logic_error, which add’s contract never mentions
add(song) refuses only a bad song, with std::invalid_argument No. It refuses every song, with a different exception
remove_at(i) removes the song at i, or throws std::out_of_range No. It throws std::logic_error even for a valid i
name(), size(), at(i) read the list Yes

Three broken promises, all in the editing half. The reading half is fine. That split is the clue to the fix.

Before, Chart inherits editing it must refuse; after, both lists share only a read-only interface, and only Playlist can edit
Text description of the diagram

Two parts, before and after. Before: Chart, whose add and remove_at throw, has a thick “is a” arrow to Playlist, which has name, size, at, add, and remove_at. The add_missing function, whose destination is a Playlist, has a dashed arrow labelled “edits” to Playlist. After: Playlist, which has add and remove_at, and Chart, which has plays_at, each have a thick “implements” arrow to the SongList interface, which has name, size, and at. The add_missing function now takes a Playlist as its destination and a const SongList as its source; it has a dashed “edits” arrow to Playlist and a dashed “reads” arrow to SongList. No arrow connects Chart to Playlist. A flow arrow from the Before group to the After group shows the redesign.

Diagram source (Mermaid)
flowchart TB
subgraph Before
  BC["Chart<br/>add, remove_at: throw"] ==>|is a| BP["Playlist<br/>name, size, at, add, remove_at"]
  BA["add_missing<br/>destination: Playlist"] -.->|edits| BP
end
subgraph After
  AP["Playlist<br/>add, remove_at"] ==>|implements| AS["SongList<br/>name, size, at"]
  AC["Chart<br/>plays_at"] ==>|implements| AS
  AA["add_missing<br/>destination: Playlist<br/>source: const SongList"] -.->|edits| AP
  AA -.->|reads| AS
end
Before --> After

struct Song

a value: title and length

Data members

  • std::string title;
  • std::chrono::seconds length;

interface (abstract class) SongList

read-only; the contract is written in the header

Member functions

  • virtual const std::string& name() const = 0; never empty
  • virtual std::size_t size() const = 0;
  • virtual const Song& at(std::size_t index) const = 0; throws std::out_of_range if index >= size()
  • virtual ~SongList() = default;
  • SongList(const SongList&) = default; protected, as are the default constructor and operator=

class Playlist final

implements SongList; the listener edits it

Data members

  • std::string name_;
  • std::vector<Song> songs_;

Member functions

  • explicit Playlist(std::string name); throws if the name is empty
  • void add(Song song); then size() is one larger and at(size() - 1) is song
  • void remove_at(std::size_t index); throws std::out_of_range

struct ChartEntry

a song and how often it was played

Data members

  • Song song;
  • long long plays;

class Chart final

implements SongList; nobody edits it

Data members

  • std::string name_;
  • std::vector<ChartEntry> entries_; sorted, most played first

Member functions

  • Chart(std::string name, std::vector<ChartEntry> entries); throws on bad input
  • long long plays_at(std::size_t index) const;

namespace song_lists

free functions, written once against SongList

Functions

  • std::chrono::seconds total_length(const SongList& list);
  • bool contains(const SongList& list, std::string_view title);
  • std::size_t add_missing(Playlist& playlist, const SongList& from);
After: one read-only contract, two implementations with different storage, and editing only in Playlist

(In the code, the three free functions are at namespace scope; the song_lists box only groups them.)

The copy operations are protected so that code cannot assign one list to another through SongList&: that would copy only the SongList part of each object (called slicing), which here is nothing at all.

The contract, written where callers see it. The interface is only the reading half, and its comment states the whole contract. The two free functions are written once, against that contract, and work for every SongList, including ones that do not exist yet.

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

song_list.hpp
// Read-only access to an ordered list of songs. This is the whole
// contract every implementation must keep:
// - name() is never empty;
// - at(i) returns the song at position i for every i < size(), and
// throws std::out_of_range for i >= size();
// - reading never changes the list.
// It is an interface: `= 0` makes each function "pure virtual", so
// SongList has no code of its own for them and cannot be created on its
// own. Every class derived from it must supply all three, and every one is
// `const`, so the interface offers no way to edit a list at all.
class SongList {
public:
// Virtual, so destroying a derived list through a SongList pointer
// runs the derived class's destructor too.
virtual ~SongList() = default;
virtual const std::string& name() const = 0;
virtual std::size_t size() const = 0;
virtual const Song& at(std::size_t index) const = 0;
protected:
// Protected: only derived classes may construct or copy the SongList
// part. Outside code cannot copy a Playlist or Chart into a bare
// SongList and lose the derived part ("slicing").
SongList() = default;
SongList(const SongList&) = default;
SongList& operator=(const SongList&) = default;
};
// Written once, against the contract; works for every SongList. Both use
// only size() and at(i): a loop from i = 0 while i < size(), so at(i) is
// never asked for a position that is not there.
// total_length: the sum of every song's length (0 seconds for an empty
// list).
std::chrono::seconds total_length(const SongList& list);
// contains: true if some song's title equals `title` exactly (case
// matters). It stops at the first match. std::string_view lets a caller
// pass a std::string or a "literal" without making a copy.
bool contains(const SongList& list, std::string_view title);

Editing, where it exists. Playlist keeps the same promises as the old Playlist did. Nothing is overridden to refuse.

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

playlist.hpp
// A list the listener edits. It is a SongList, and adds editing. The
// editing functions are not virtual and not in SongList, so no other kind
// of list ever has to pretend to support them. `final`: nothing derives
// from Playlist.
class Playlist final : public SongList {
public:
explicit Playlist(std::string name); // throws if the name is empty
// Postcondition: size() is one larger and at(size() - 1) is `song`.
// Throws std::invalid_argument for a song check_song refuses, and then
// the list is unchanged. `song` is taken by value (a copy the
// playlist then keeps).
void add(Song song);
// Throws std::out_of_range if there is no entry at `index`.
void remove_at(std::size_t index);
// The three reading functions SongList asks for. `override` makes the
// compiler check that each really replaces a SongList function.
// songs_.at(index) throws std::out_of_range for index >= size(), which
// is exactly what the contract promises.
const std::string& name() const override { return name_; }
std::size_t size() const override { return songs_.size(); }
const Song& at(std::size_t index) const override { return songs_.at(index); }
private:
std::string name_; // never empty: the constructor checks it
std::vector<Song> songs_; // in playing order, owned by value
};
// Adds each song from `from` whose title is not already in `playlist`,
// and returns how many it added. The parameter types say who is edited:
// Playlist& (may change) for the destination, const SongList& (read only)
// for the source. Only the destination must be editable; any SongList can
// be the source, so a Chart can be passed as `from` but never as
// `playlist`. Throws std::invalid_argument (from add) if a source song is
// refused; songs added before that stay added.
std::size_t add_missing(Playlist& playlist, const SongList& from);

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

playlist.cpp
// One pass over the source. For each song, ask the destination "do you
// already have this title?" and add it only if the answer is no.
std::size_t add_missing(Playlist& playlist, const SongList& from) {
std::size_t added = 0; // how many songs this call has added
// from.size() is read again on every step. That matters when a list
// is its own source: nothing is added then (every title is already
// there), so the size does not change and the loop still ends.
for (std::size_t i = 0; i < from.size(); ++i) {
// contains() reads the destination as a SongList; titles added
// earlier in this same loop count too, so a title that appears twice
// in `from` is added only once.
if (!contains(playlist, from.at(i).title)) {
playlist.add(from.at(i)); // add takes a copy, made before it runs
++added;
}
}
return added;
}
How this code works: add_missing

add_missing reads one list and edits the other, and its parameter types say which is which.

  1. added starts at 0. It counts the songs this call adds.
  2. The loop walks the source, from, by position: i goes from 0 up to, but not including, from.size(). Because from is a const SongList&, the loop can only read it, through size() and at(i), so any kind of SongList works here.
  3. For each source song, ask the destination. contains(playlist, title) looks through the playlist for that title. A Playlist is a SongList, so the same contains serves both.
  4. If the title is missing, add a copy. add takes its Song by value, so the copy is made from from.at(i) before add starts changing the playlist. Then added goes up by one.
  5. Return added.

A worked example, with the values from the “Check” section below. The chart, sorted by plays, is Paper Moon, Night Drive, Low Tide. The road trip starts with Long Road, Night Drive, Coastline.

i from.at(i) Already in the road trip? What happens added
0 Paper Moon no added as song 4 1
1 Night Drive yes skipped 1
2 Low Tide no added as song 5 2

The call returns 2, and the program prints “added 2 from Top of the week”.

What cannot happen. Passing the chart as the first argument does not compile: a Chart is not a Playlist, so there is no run-time failure left to find.

A different implementation, keeping the same promises. A chart stores entries with play counts, sorted, so it could never have reused Playlist’s storage anyway. It keeps SongList’s contract in its own way: at(i) returns the song part of entry i.

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

chart.hpp
// One line of the chart: a song and how many times it was played this
// week. `long long` is a wide integer type, so large counts fit.
struct ChartEntry {
Song song;
long long plays;
};
// This week's songs, most played first. A SongList with no editing at
// all: there is nothing to override and nothing to refuse.
class Chart final : public SongList {
public:
// Sorts by plays, most first; equal plays keep their given order.
// Throws std::invalid_argument for an empty name, a bad song, or
// negative plays. Both arguments are taken by value and moved into
// the members, so the chart owns its own copy of the entries. All
// checking and sorting happen here, once: after construction there is
// no function that can change a Chart.
Chart(std::string name, std::vector<ChartEntry> entries);
// SongList's three reading functions, kept in Chart's own way: at(i)
// returns the song part of entry i. entries_.at(index) throws
// std::out_of_range for a bad index, the same failure the contract
// promises.
const std::string& name() const override { return name_; }
std::size_t size() const override { return entries_.size(); }
const Song& at(std::size_t index) const override { return entries_.at(index).song; }
// An extra, Chart-only reader. It is not part of SongList, so code
// written against SongList neither sees nor needs it.
long long plays_at(std::size_t index) const { return entries_.at(index).plays; }
private:
std::string name_;
std::vector<ChartEntry> entries_; // different storage from Playlist
};
Choice Why What it costs
A read-only base, SongList Every list can keep the reading promises; only some can keep editing ones One more type
add_missing(Playlist&, const SongList&) The parameter types say what the function does to each: edit one, read the other A caller with a bare std::vector<Song> must wrap it in a SongList, or you keep an overload
Playlist and Chart are final Nobody should derive from them; new kinds of list implement SongList Reuse their code by composition, not inheritance
total_length and contains are free functions They need only the public contract, so they work for every SongList, and no implementation can get them wrong A call is total_length(list) rather than list.total_length()
at throws std::out_of_range, as std::vector::at does One documented failure, the same for every implementation A bounds check on every call
No editable() flag, no dynamic_cast The type system answers “may I edit?” at compile time A function that needs to edit or read must say which it needs

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

main.cpp
// A playlist with the three songs in `mine`. add takes each song by
// value, so the playlist keeps its own copies.
Playlist road_trip{"Road trip"};
for (const Song& song : mine) road_trip.add(song);
// A chart built from three { song, plays } entries. Each innermost pair
// of braces is a Song, e.g. {"Night Drive", 210s}; 210s means 210 seconds
// (from std::chrono_literals). The constructor sorts by plays, so the
// order becomes Paper Moon (1200), Night Drive (900), Low Tide (450).
const Chart chart{"Top of the week", {{{"Night Drive", 210s}, 900},
{{"Paper Moon", 224s}, 1200},
{{"Low Tide", 178s}, 450}}};
// The chart is a source, never a destination:
// add_missing(chart, road_trip) does not compile.
// Night Drive is already in the road trip, so only Paper Moon and
// Low Tide are added: the call returns 2. show prints a whole list
// through SongList only, so the same function serves both kinds.
std::cout << " added " << add_missing(road_trip, chart) << " from " << chart.name()
<< '\n';
show(chart);
show(road_trip);
Expected output
before:
added 1 to Road trip
Top of the week: a chart cannot be edited
after:
added 2 from Top of the week
Top of the week: 3 songs, 10:12
1. Paper Moon 3:44
2. Night Drive 3:30
3. Low Tide 2:58
Road trip: 5 songs, 19:29
1. Long Road 4:05
2. Night Drive 3:30
3. Coastline 5:12
4. Paper Moon 3:44
5. Low Tide 2:58

Before, both calls compiled; the one with a chart as destination failed at run time. After, the chart is used only as a source, and the commented call that would use it as a destination does not compile.

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

test_song_lists.cpp
// 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.
// The flaw, pinned: code written for Playlist fails on a Chart. The test
// holds the old Chart through a Playlist& (allowed, because a
// before::Chart is a Playlist) and proves add_missing then throws
// std::logic_error. Low Tide is not in the chart, so add_missing does try
// to add it.
LLD_TEST(before_a_chart_breaks_code_written_for_playlists) {
before::Chart chart{"Top", {{"Paper Moon", 224s}}};
before::Playlist& playlist = chart;
LLD_CHECK_THROWS(before::add_missing(playlist, {{"Low Tide", 178s}}), std::logic_error);
}
// One contract test, run against every implementation of SongList.
// It takes the list as a const SongList&, so it can use only the contract,
// and `titles` is what the list should hold, in order. Each check is one
// promise from SongList's comment. (namespace { } keeps the helper private
// to this file.)
namespace {
void check_song_list_contract(const SongList& list, const std::vector<std::string>& titles) {
LLD_CHECK(!list.name().empty()); // name() is never empty
LLD_CHECK(list.size() == titles.size()); // the right number of songs
// The songs, in order. The loop stops at the shorter of the two, so a
// wrong size (already reported above) cannot make it read past an end.
for (std::size_t i = 0; i < titles.size() && i < list.size(); ++i) {
LLD_CHECK(list.at(i).title == titles[i]);
}
// total_length, the shared free function, agrees with adding up the
// lengths by hand.
std::chrono::seconds sum{0};
for (std::size_t i = 0; i < list.size(); ++i) sum += list.at(i).length;
LLD_CHECK(sum == total_length(list));
// One past the last position is out of range, and must throw.
LLD_CHECK_THROWS(list.at(list.size()), std::out_of_range);
}
} // namespace
// The same checks on three lists: an empty playlist, a playlist with one
// song, and a chart. The chart is given plays 3 and 7, so after sorting
// Low Tide (7) comes before Paper Moon (3).
LLD_TEST(every_song_list_keeps_the_contract) {
Playlist playlist{"Mine"};
check_song_list_contract(playlist, {}); // empty
playlist.add({"Long Road", 245s});
check_song_list_contract(playlist, {"Long Road"});
check_song_list_contract(Chart{"Top", {{{"Paper Moon", 224s}, 3}, {{"Low Tide", 178s}, 7}}},
{"Low Tide", "Paper Moon"});
}
// The fix, pinned at compile time: a chart cannot be a destination.
// static_assert stops the build if its condition is false, so these are
// tests that run in the compiler. std::is_invocable_v<F, Args...> is true
// when a function of type F can be called with those argument types;
// decltype(&add_missing) is the type of a pointer to add_missing.
// 1. add_missing(Playlist&, const Chart&) compiles: chart as a source;
// 2. add_missing(Chart&, const Playlist&) does not: chart as destination;
// 3. a Chart* cannot convert to a Playlist*: a Chart is not a Playlist.
static_assert(std::is_invocable_v<decltype(&add_missing), Playlist&, const Chart&>);
static_assert(!std::is_invocable_v<decltype(&add_missing), Chart&, const Playlist&>);
static_assert(!std::is_convertible_v<Chart*, Playlist*>);
// add's promise: one more song, and the new song is last.
LLD_TEST(add_keeps_its_postcondition) {
Playlist playlist{"Mine"};
playlist.add({"Long Road", 245s});
playlist.add({"Coastline", 312s});
LLD_CHECK(playlist.size() == 2);
LLD_CHECK(playlist.at(1).title == "Coastline");
}
// The playlist already has Night Drive, so from the chart only Paper Moon
// is added, and it goes at the end (position 1).
LLD_TEST(add_missing_skips_titles_already_there) {
Playlist playlist{"Mine"};
playlist.add({"Night Drive", 210s});
const Chart chart{"Top", {{{"Night Drive", 210s}, 900}, {{"Paper Moon", 224s}, 1200}}};
LLD_CHECK(add_missing(playlist, chart) == 1);
LLD_CHECK(playlist.at(1).title == "Paper Moon");
LLD_CHECK(add_missing(playlist, playlist) == 0); // as its own source, a list adds nothing
}
// Given A (5 plays), B (9), C (5): B comes first, and A and C, tied on 5,
// keep the order they were given in. That is what a stable sort promises.
LLD_TEST(chart_orders_by_plays_and_keeps_ties_in_order) {
const Chart chart{"Top", {{{"A side", 100s}, 5}, {{"B side", 100s}, 9}, {{"C side", 100s}, 5}}};
LLD_CHECK(chart.at(0).title == "B side");
LLD_CHECK(chart.at(1).title == "A side");
LLD_CHECK(chart.at(2).title == "C side");
LLD_CHECK(chart.plays_at(0) == 9);
}
// Every refusal throws the documented exception, and a refused add
// leaves the playlist empty. The extra brackets around Chart{...} keep
// the macro from reading the commas inside the braces as separate macro
// arguments.
LLD_TEST(bad_input_is_refused) {
Playlist playlist{"Mine"};
LLD_CHECK_THROWS(playlist.add({"", 100s}), std::invalid_argument);
LLD_CHECK_THROWS(playlist.add({"Silence", 0s}), std::invalid_argument);
LLD_CHECK(playlist.size() == 0);
LLD_CHECK_THROWS(playlist.remove_at(0), std::out_of_range);
LLD_CHECK_THROWS(Playlist{""}, std::invalid_argument);
LLD_CHECK_THROWS((Chart{"Top", {{{"Hit", 100s}, -1}}}), std::invalid_argument);
}

The central test is check_song_list_contract: one set of checks, written against SongList’s contract, run against every implementation (an empty playlist, a playlist with a song, and a chart). This is how you test LSP in practice: when you add a new kind of SongList, run the same contract test against it. Passing does not prove every promise is kept, but a failure shows a broken one before any caller finds it. The static_assert lines check the fix at compile time: a chart is not a Playlist, and add_missing does not accept one as its destination.

  • The contract test checks what can be checked from outside: the name, the songs in order, the bounds, and the total. Some promises (“reading never changes the list”) are checked only by reading the code.
  • contains and add_missing scan the list for each song, so adding n songs to a playlist of m is O(n × m). Fine for playlists; a large catalogue would keep a set of titles.
  • Song titles are compared exactly: “Night Drive” and “night drive” are different songs.
  • at returns a reference into the list. It stays valid until that list is changed; after add or remove_at on a playlist, an earlier reference may dangle, or quietly refer to a different song.

The chart is one shape of a common mistake. Here are the others you will meet, and what each breaks:

Violation What it breaks Typical fix
An override that throws “not supported” Postcondition (a failure the base never mentioned) Split the interface; give the derived class only what it can do
An override that quietly does nothing Postcondition, silently The same; this one is harder to find
An override that needs more (“only after connect()”) Precondition, made stronger Make the need explicit in the type (a connected object), or in the base contract
An override that returns a value outside the promised range (a discount of 120 % when the base promises 0 to 100) Postcondition, made weaker Fix the override, or check the range in a non-virtual base function
A derived class that changes protected data so the base’s invariant no longer holds Invariant Keep data private in the base; give derived classes functions, not data
A mutable Square derived from a mutable Rectangle Postcondition of the setters Do not derive; or make both immutable

The last row is the best-known example. It is worth seeing in code, because every line looks reasonable:

// A rectangle whose sides can be changed one at a time.
class Rectangle {
public:
Rectangle(int width, int height) : width_{width}, height_{height} {}
virtual ~Rectangle() = default;
// Postcondition: width() == width, and height() is unchanged.
virtual void set_width(int width) { width_ = width; }
// Postcondition: height() == height, and width() is unchanged.
virtual void set_height(int height) { height_ = height; }
int width() const { return width_; }
int height() const { return height_; }
int area() const { return width_ * height_; }
protected: // protected only to keep the sketch short
int width_;
int height_;
};
// A square "is a" rectangle in geometry, so it derives from Rectangle.
class Square final : public Rectangle {
public:
// Builds the Rectangle part with equal sides.
explicit Square(int side) : Rectangle{side, side} {}
// Keeps the square square, and so breaks Rectangle's postcondition.
// `width_ = height_ = width` sets both sides: the right-hand
// assignment happens first, and its result is assigned to width_.
void set_width(int width) override { width_ = height_ = width; }
void set_height(int height) override { width_ = height_ = height; }
};
// Doubles the width and returns the new area. Correct for any shape that
// keeps Rectangle's promise; set_width is virtual, so a Square's version
// runs when `shape` is really a Square.
int widened_area(Rectangle& shape) { // written for rectangles
shape.set_width(shape.width() * 2);
return shape.area(); // expects twice the old area
}

widened_area on a 3 × 4 rectangle returns 24, twice the old 12, as expected. On a 3 × 3 square it returns 36, four times the old 9, because set_width also changed the height. Square keeps its own invariant (all sides equal) only by breaking Rectangle’s promise that set_width leaves the height alone.

The problem is not “squares and rectangles”; it is the setters. If both are immutable values (no set_width, only constructors and width(), height(), area()), a square is substitutable for a rectangle for every one of those operations: every promise is about reading, and a square keeps them all. (Add a new promise, such as an equality rule or a function that returns a changed copy, and you must check it again.) When a hierarchy keeps failing LSP, look at the mutating functions first.

  • The base contract allows the behaviour. If Sink::write is documented as “may throw WriteError”, a derived sink that throws WriteError keeps the contract. Throwing is not a violation in itself; throwing what the contract does not allow is.
  • The inheritance is not public. With private (or protected) inheritance, outside code cannot convert a derived object to the base, so the derived class makes no promise to callers. (It is usually better written as composition; see composition versus inheritance.) Public inheritance always makes the promise, even if it was meant “only to share code” and nobody uses a base reference today.
  • Templates and concepts. Code like template <SongListLike L> has the same question in a different form: every type that satisfies the concept must keep the behaviour the template relies on, not just compile. A concept checks syntax, not promises.
You gain You pay
Code written against a base works for every derived class, including future ones You must write the contract down, and check every new class against it
Wrong uses become compile errors instead of run-time failures More, smaller types (SongList and Playlist instead of one)
One contract test covers every implementation Hierarchies need redesigning when a new kind does not fit, rather than an override that refuses
  • Deciding inheritance from nouns. “A chart is a playlist”, “a penguin is a bird”. Decide from the contract: what may callers do, and what do they get back?
  • Refusing in an override. throw std::logic_error{"not supported"} in an override is a sign the base class promises too much.
  • Fixing it in the callers. dynamic_cast or typeid checks before calling a virtual function move the problem to every caller.
  • Leaving the contract unwritten. If the base class’s header does not say what add promises, nobody can check a derived class against it. Write preconditions, postconditions, and errors in the comments (see errors and failure contracts).
  • Testing each class only on its own. A derived class’s own tests can all pass while it breaks the base’s contract. Run the base’s contract test against it too.

Smart playlists: “all my songs under three minutes”, computed from the listener’s library. A new kind of list nobody edits directly. It implements SongList, passes check_song_list_contract, and add_missing, total_length, and contains work with it unchanged. This is the open/closed principle working because LSP holds.

Moderators must be able to remove a song from a chart. Tempting: give Chart a remove_at. But this is an edit made by the chart service, not by listeners, and listeners see charts through SongList (read-only) anyway, so adding a function to Chart does not break any contract. Whether it is the right design is another question: if charts are published weekly, building a new Chart without the song is simpler and keeps every published chart unchanged.

Collaborative playlists that only their owner may reorder. If “reorder” is added to Playlist and a collaborative playlist refuses it for non-owners, you are back at the start of this page. (Playlist is final, so the collaborative kind would be a second editable type sharing a new base with Playlist; that base’s reorder contract is where the question lands.) The precondition (“only the owner”) is part of the operation, so it belongs in the operation’s type or arguments (for example, reordering takes the person asking and returns whether it was allowed), for every playlist.

Exercise: Spot the LSP violation

For each pair, say whether the derived class can be substituted for the base class. If not, say which part of the contract it breaks, and how you would redesign.

  1. Account::withdraw(int cents), documented as “precondition: cents <= balance(); afterwards the balance is cents lower”. SavingsAccount::withdraw throws std::runtime_error after three withdrawals in a month.
  2. Logger::log(std::string_view message), documented as “may drop the message (for example, when the logger is busy); never throws”. NullLogger::log does nothing at all.
  3. Bird::fly(), documented as “afterwards altitude() > 0”. Penguin::fly() throws std::logic_error{"penguins cannot fly"}.
  4. Shape::area(), documented as “returns the area, never negative”. Circle and Square are immutable and each compute their own area.
Show the explained answer

1. Violation: a stronger precondition. Callers of Account& only check cents <= balance(); a savings account demands more (“and fewer than three this month”), and fails with an error the base never mentions. (You can describe the same flaw as a weaker postcondition: for a valid call, it reports an error the base never listed. Both views lead to the same fix.) Two honest fixes. If every account may refuse a withdrawal, put that in the base contract: bool try_withdraw(int cents) (or one that returns a reason), so all callers handle refusal. If only savings accounts have the limit, withdraw should not be on a shared base that promises it always works; callers that withdraw take the kind of account that allows it.

2. Not a violation. The contract allows dropping any message (“when busy” is only an example), so a logger that drops all of them keeps every promise. (Whether a NullLogger is useful is a separate question; for tests it often is.) This is why writing the contract down matters: with “every message is written” as the contract, the same class would be a violation.

3. Violation: a weaker postcondition. Code that calls bird.fly() and then reads the altitude is wrong for a penguin. Do not fix it with if (bird.can_fly()) in every caller. Redesign: fly does not belong on Bird. Put it on a Flyer interface that flying birds implement, and let code that needs flight ask for a Flyer&. (A can_fly() query is honest only if flying is optional for every bird and Bird::fly’s contract says so, as in the “better” option above; then every caller must check, with the costs listed there.)

4. Substitutable. Both keep “returns the area, never negative”, and there are no setters whose promises could be broken. Immutable values are the easiest hierarchies to keep LSP-correct.

  • LSP: code that works with a base type must keep working, unchanged, with any derived type.
  • Check it with the contract: a derived class may not ask for more (preconditions), promise less (postconditions), or break the base’s invariants.
  • “Is a” in English is not enough; “keeps the contract” is the test.
  • An override that throws “not supported”, or does nothing, means the base promises too much. Split the hierarchy so each type promises only what it can do, and let parameter types say what a function needs.
  • Avoid fixing violations in the callers with type checks; that breaks the open/closed principle too.
  • Test substitutability with one contract test run against every implementation.