Inheritance, virtual functions, and interfaces
What you will learn on this page
Section titled “What you will learn on this page”- How to declare an interface: a class of pure virtual functions that other code depends on.
- How
virtual,override, andfinalwork, and why each matters. - Why a base class used through pointers needs a virtual destructor.
- How to make object slicing impossible.
- The non-virtual interface idea: a base class that enforces rules for every implementation.
The problem: one job, several ways to do it
Section titled “The problem: one job, several ways to do it”A library sends reminders to members whose loans are due. Some members have an email address, some only a phone number, and next year there may be a mobile app. The code that decides when to send a reminder should not change every time a new way of sending one is added.
The design tool for this is an interface: a description of what an operation does, separate from any particular way of doing it. Code that sends reminders depends only on the interface; each channel (email, SMS) is a separate class that implements it. In C++, an interface is a class whose member functions are pure virtual.
Declaring an interface
Section titled “Declaring an interface”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Interface: one way of delivering a reminder to a member. It says WHAT a// channel can do (send a message, name itself) and nothing about HOW. It// has no data members and no function bodies of its own, so it is a pure// interface. Because its functions are pure virtual (`= 0`), the class is// abstract: you cannot create a Notifier, only an object of a class that// derives from it and supplies every function.class Notifier {public: // Virtual destructor: when a std::unique_ptr<Notifier> deletes an // EmailNotifier through its Notifier*, `virtual` makes C++ run // ~EmailNotifier first and then ~Notifier, so the derived part (its // outbox) is destroyed too. `= default` asks for the normal destructor. virtual ~Notifier() = default; // deleting through Notifier* is safe
// Delivers message. Returns false if this channel cannot deliver it. // `virtual` means a call through a Notifier& or Notifier* runs the // version of the real object (email or SMS), chosen at run time. // `= 0` means "no body here: every concrete channel must write one". [[nodiscard]] virtual bool send(const Message& message) = 0; // The channel's short name, such as "email". std::string_view is a // read-only view of characters stored elsewhere; here it views a string // literal, which lives for the whole program, so the view never dangles. [[nodiscard]] virtual std::string_view channel() const noexcept = 0;
protected: // Only derived classes may copy or move the base part, so a Notifier // can never be sliced out of a derived object. Declaring the destructor // above would stop the compiler from writing the moves for us, so the // copies and moves are all listed and defaulted here. Code outside the // hierarchy cannot call them, so `Notifier copy = email;` does not // compile. The default constructor must be listed too: declaring a copy // constructor removes the one the compiler would otherwise provide. Notifier() = default; Notifier(const Notifier&) = default; Notifier& operator=(const Notifier&) = default; Notifier(Notifier&&) = default; Notifier& operator=(Notifier&&) = default;};Line by line:
virtualmakes a function dispatch on the object’s real type. When code callssendthrough aNotifier&orNotifier*, the version for the actual object (email or SMS) runs. This is decided at run time, typically through a hidden table of function pointers that each polymorphic object refers to (the standard does not require that mechanism, but compilers use it).= 0makes the function pure virtual:Notifierprovides no implementation, and every concrete derived class must. A class with at least one pure virtual function is abstract: you cannot create aNotifierobject, only objects of derived classes.virtual ~Notifier() = default;is the virtual destructor. The service below owns channels throughstd::unique_ptr<Notifier>, which deletes them through aNotifier*. Only a virtual destructor makes that delete run the derived class’s destructor (more below).- The protected special members follow the previous lesson: declaring the
virtual destructor would otherwise suppress the moves, and public copies would
allow slicing. Making them
protectedand= defaultlets derived classes copy themselves, while outside code cannot copy aNotifierout of one.
Implementing it: override and final
Section titled “Implementing it: override and final”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Stand-in for a mail server: accepted messages are kept in an outbox.// `: public Notifier` says an EmailNotifier IS A Notifier, so it can be// passed wherever a Notifier& or Notifier* is expected.class EmailNotifier : public Notifier {public: // Accepts recipients that contain '@' and stores a copy of the message; // returns false, storing nothing, for any other recipient. `override` // asks the compiler to check that this really replaces Notifier::send: // a mismatch (a missing const, a different parameter) is then an error // instead of a silent new function. [[nodiscard]] bool send(const Message& message) override; [[nodiscard]] std::string_view channel() const noexcept override { return "email"; } [[nodiscard]] const std::vector<Message>& outbox() const noexcept { return outbox_; }
private: std::vector<Message> outbox_;};
// final: no class may derive from SmsNotifier.class SmsNotifier final : public Notifier {public: // The longest text one SMS may carry. static: one value shared by the // class, not stored in each object. constexpr: fixed at compile time. static constexpr std::size_t max_length = 160;
// Accepts recipients that start with '+' and texts up to max_length // characters (160 is allowed, 161 is not); returns false otherwise. [[nodiscard]] bool send(const Message& message) override; [[nodiscard]] std::string_view channel() const noexcept override { return "sms"; } [[nodiscard]] std::size_t sent() const noexcept { return sent_.size(); }
private: std::vector<Message> sent_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Email's rule: the recipient must contain an '@' somewhere.bool EmailNotifier::send(const Message& message) { // find returns the position of the first '@', or the special value // std::string::npos ("no position") when there is none. if (message.recipient.find('@') == std::string::npos) return false; outbox_.push_back(message); // keeps its own copy; the caller's is untouched return true;}
// SMS's rules: the recipient starts with '+', and the text fits in one SMS.// Each check returns false at once, so a refused message is never stored.bool SmsNotifier::send(const Message& message) { // empty() is tested first: front() on an empty string is undefined // behaviour, and `||` stops as soon as its left side is true. if (message.recipient.empty() || message.recipient.front() != '+') return false; if (message.text.size() > max_length) return false; sent_.push_back(message); return true;}: public Notifierdeclares that anEmailNotifieris aNotifier: it can be used anywhere aNotifier&orNotifier*is expected. Usepublicinheritance for this relationship; the classes and access lesson noted thatclassinherits privately by default.overridesays “this function replaces a virtual function of the base”. If the signature does not match exactly, for example becauseconstis missing or a parameter type differs, the compiler reports an error. Withoutoverride, a mismatch silently declares a new function, and calls through the base never reach it. Writeoverrideon every overriding function.finalon a class forbids deriving from it.SmsNotifieris markedfinalbecause nothing needs to specialize it, and saying so means nobody has to design it for that. (finalcan also be put on a single virtual function.)
Each implementation adds its own state (an outbox, a list of sent messages) and
its own rules (email needs an @, SMS needs a + and at most 160 characters),
while honouring the interface’s contract: return true if delivered, false if
this channel cannot deliver.
Code that depends only on the interface
Section titled “Code that depends only on the interface”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Tries each channel in the order added until one accepts the message.// Depends only on the Notifier interface, so new channels need no change here.class ReminderService {public: // Takes ownership of one channel. The parameter is a std::unique_ptr by // value, so the caller must hand it over with std::move (or pass a // fresh std::make_unique<...>()); afterwards the service alone owns it. // Throws std::invalid_argument if notifier is null. void add_channel(std::unique_ptr<Notifier> notifier); // Returns the channel that delivered the message, or "" if none could. [[nodiscard]] std::string remind(const Message& message);
private: // The channels, in the order they were added. Owning pointers, not // Notifier values: Notifier is abstract, and a vector of values would // slice each channel down to its base part. When the service is // destroyed, each unique_ptr deletes its channel (virtually, see above). std::vector<std::unique_ptr<Notifier>> channels_; // owns; never null};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Refuses a null pointer up front, so every element of channels_ points at a// real channel and remind never has to check.void ReminderService::add_channel(std::unique_ptr<Notifier> notifier) { if (notifier == nullptr) throw std::invalid_argument("a channel must not be null"); // A unique_ptr cannot be copied, only moved: std::move hands ownership // from the parameter to the new element, leaving the parameter null. channels_.push_back(std::move(notifier));}
// Asks each channel in turn, first added first, and stops at the first one// that accepts. Returns that channel's name, or "" if every channel refused.std::string ReminderService::remind(const Message& message) { // Each element is borrowed by const reference: a unique_ptr cannot be // copied, and the loop must not take ownership away from the vector. for (const std::unique_ptr<Notifier>& notifier : channels_) { // `->` calls through the pointer. send and channel are virtual, so // EmailNotifier::send runs for an email channel, SmsNotifier::send // for an SMS one. channel() returns a string_view; std::string(...) // copies it into the string this function returns. if (notifier->send(message)) return std::string(notifier->channel()); // virtual calls } return ""; // no channel could deliver the message}How this code works: ReminderService::remind
remind walks the channels in the order they were added and stops at the
first one that says yes.
- The loop.
for (const std::unique_ptr<Notifier>& notifier : channels_)looks at each owning pointer in turn without copying it (aunique_ptrcannot be copied) and without taking it out of the vector. - The virtual call.
notifier->send(message)is written once, againstNotifier. At run time it runsEmailNotifier::sendif the pointer holds an email channel, orSmsNotifier::sendif it holds an SMS channel. - Stop at the first success. If
sendreturnstrue, the function returns that channel’s name at once, so later channels are never asked. - Nobody could deliver. If the loop finishes, every channel said
false, and the function returns an empty string.
A worked example, with the channels and reminders from main below (email
added first, then SMS):
| Recipient | EmailNotifier::send |
SmsNotifier::send |
remind returns |
|---|---|---|---|
"ada@example.org" |
has @: true |
not asked | "email" |
"+447700900123" |
no @: false |
starts with +, text is 20 characters: true |
"sms" |
"unknown" |
no @: false |
no +: false |
"" |
ReminderService owns its channels through std::unique_ptr<Notifier>, because
they are polymorphic: a vector cannot hold Notifier values (the class is
abstract, and values would slice), so it holds owning pointers. The service never
names EmailNotifier or SmsNotifier. Adding a push-notification channel later
means writing one new class and adding it with add_channel; ReminderService
does not change.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
ReminderService service;// std::make_unique<EmailNotifier>() creates an EmailNotifier on the heap// and returns a std::unique_ptr<EmailNotifier> that owns it. It converts// to std::unique_ptr<Notifier> on the way in, and the service now owns// it. The order matters: email is tried first, then SMS.service.add_channel(std::make_unique<EmailNotifier>());service.add_channel(std::make_unique<SmsNotifier>());
// Three reminders, each built from {recipient, text}: one email address,// one phone number, and one that neither channel accepts.const std::vector<Message> reminders{ {"ada@example.org", "Middlemarch is due tomorrow"}, {"+447700900123", "Emma is due tomorrow"}, {"unknown", "Ivanhoe is overdue"},};for (const Message& reminder : reminders) { const std::string channel = service.remind(reminder); // `?:` picks "not delivered" when remind returned "", otherwise // "sent by email" or "sent by sms". std::cout << reminder.recipient << ": " << (channel.empty() ? "not delivered" : "sent by " + channel) << '\n';}ada@example.org: sent by email+447700900123: sent by smsunknown: not deliveredText description of the diagram
Four boxes. A solid arrow labelled “owns 0..*, unique_ptr” goes from
ReminderService to Notifier, an interface. Thick “implements” arrows go
from EmailNotifier and from SmsNotifier, which is marked final, to
Notifier. No arrow joins ReminderService to either implementation.
Diagram source (Mermaid)
flowchart LR
ReminderService -->|"owns 0..*, unique_ptr"| Notifier["Notifier (interface)"]
EmailNotifier ==>|implements| Notifier
SmsNotifier["SmsNotifier (final)"] ==>|implements| Notifierinterface (abstract class) Notifier
copy and move are protected, so it cannot be sliced by accident
Member functions
virtual ~Notifier() = default;virtual bool send(const Message& message) = 0;virtual std::string_view channel() const noexcept = 0;
class EmailNotifier
implements Notifier
Data members
std::vector<Message> outbox_;
Member functions
bool send(const Message& message) override;std::string_view channel() const noexcept override;"email"const std::vector<Message>& outbox() const noexcept;
class SmsNotifier
final; implements Notifier
Data members
std::vector<Message> sent_;static constexpr std::size_t max_length = 160;public
Member functions
bool send(const Message& message) override;std::string_view channel() const noexcept override;"sms"std::size_t sent() const noexcept;
class ReminderService
depends only on Notifier
Data members
std::vector<std::unique_ptr<Notifier>> channels_;owns; never null
Member functions
void add_channel(std::unique_ptr<Notifier> notifier);throws std::invalid_argument if nullstd::string remind(const Message& message);the delivering channel's name, or "" if none
Why the destructor must be virtual
Section titled “Why the destructor must be virtual”Deleting an object through a pointer to its base class runs the destructor that the pointer’s type names, unless that destructor is virtual. Here a plain struct, never designed as a base class, has been derived from:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Written as a plain record, not designed as a base class.struct Record { int id = 0; // Spelled out here only to make the point visible: this destructor is // NOT virtual, so a delete through a Record* does not look for a derived // class's destructor. If the object is really a LoanRecord, that delete // is undefined behaviour; in practice only ~Record runs. ~Record() = default; // not virtual};
// Someone derives from it to "reuse" the id member. (A struct inherits// publicly by default.) LoanRecord adds a std::string, which owns heap// memory that only ~LoanRecord would free.struct LoanRecord : Record { std::string title;};
void store() { // A vector of owning pointers to the BASE type. Each element will one // day call `delete` on a Record*. std::vector<std::unique_ptr<Record>> records; // A LoanRecord on the heap, owned by a std::unique_ptr<LoanRecord>. auto loan = std::make_unique<LoanRecord>(); // Long enough that the string stores its characters on the heap rather // than inside the string object itself. loan->title = "A title long enough to be allocated on the heap"; // Compiles without complaint: unique_ptr<LoanRecord> converts to // unique_ptr<Record>. The new owner remembers only "this is a Record", // so the information "really a LoanRecord" is lost right here. records.push_back(std::move(loan)); // At the closing brace, records is destroyed, and with it the pointer.} // ~unique_ptr<Record> calls delete on a Record*: undefined behaviour, // and in practice ~LoanRecord never runs, so `title` leaksHow this code works: what goes wrong when store() ends
std::make_unique<LoanRecord>()creates aLoanRecordon the heap. It has two parts: theRecordpart (id) and theLoanRecordpart (title).loan->title = ...makes the string allocate heap memory for its characters. Only the string’s destructor, run by~LoanRecord, frees it.records.push_back(std::move(loan))moves ownership into astd::unique_ptr<Record>. The pointer now only knows “this is aRecord”.- At the closing brace of
store,recordsis destroyed, and itsunique_ptr<Record>runsdeleteon aRecord*. - Because
~Recordis not virtual,deletedoes not look up the real type. The standard calls this undefined behaviour: nothing is promised. What usually happens is that only~Recordruns,~LoanRecordis skipped, and the string’s characters are never freed.
The fix is not in store: Record was never meant to be a base class. Either
do not derive from it (give LoanRecord a Record member instead), or, if it
really is a base used through pointers, give it a virtual destructor, as
Notifier has.
When the vector is destroyed, std::unique_ptr<Record> calls delete on a
Record*. Because ~Record is not virtual, this has
undefined behaviour; nothing
about the outcome is guaranteed. Typically, ~LoanRecord does not run, and the
title string’s memory leaks.
Compilers help only partly. When the base class has virtual functions, GCC 11 and
Clang 14 warn about a plain delete through the base pointer (GCC’s
-Wdelete-non-virtual-dtor and Clang’s equivalent, both enabled by -Wall), and
Clang 14 also warns when a std::unique_ptr does the deleting; GCC 11 does not.
When the base has no virtual functions, as here, neither compiler warns, which is why this example is compiled
to show it but never run.
The rules:
- A class meant to be used through base pointers (in practice, any class with
virtual functions whose objects are owned through a base pointer) gets a public
virtual destructor. A base class whose objects are never deleted through it can
instead have a
protected, non-virtual destructor, which makes such a delete a compile error. - A class not meant as a base gets no virtual functions and should not be
derived from. Mark it
finalif there is any doubt.
Slicing, and how the interface prevents it
Section titled “Slicing, and how the interface prevents it”The value semantics lesson showed that copying a derived object into a base-class value keeps only the base part. A container of base-class values does that to every element:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// A small polymorphic class: text() is virtual, so DueSoon can replace it.// Nothing stops it being copied by value, which is the problem below.class Reminder {public: virtual ~Reminder() = default; [[nodiscard]] virtual std::string text() const { return "Library reminder"; }};
class DueSoon : public Reminder {public: [[nodiscard]] std::string text() const override { return "Your loan is due soon"; }};
void send_all() { // Each element is a whole Reminder object, exactly sizeof(Reminder) // bytes. There is no room in it for anything a derived class adds. std::vector<Reminder> queue; // stores Reminder values // DueSoon{} is a temporary DueSoon. push_back accepts it because a // DueSoon is a Reminder, then builds a new Reminder from the Reminder // part only (this is slicing). The new element is a plain Reminder, so // its virtual calls run Reminder's versions. The temporary is then // destroyed; nothing of the DueSoon survives. queue.push_back(DueSoon{}); // copies only the Reminder part for (const Reminder& reminder : queue) { // A virtual call, but the object really is a Reminder now, so the // DueSoon override never runs. std::cout << reminder.text() << '\n'; // prints "Library reminder" }}queue stores Reminder objects, so push_back(DueSoon{}) copies only the
Reminder part. The loop prints “Library reminder”; the override never runs. It
compiles without a warning, and it is not undefined behaviour, just wrong.
The Notifier design makes this mistake impossible in two ways. Notifier is
abstract, so it cannot be passed by value or added to a std::vector<Notifier>.
And its copy operations are protected, so even through a reference,
Notifier copy = email; does not compile. Polymorphic objects are held through
std::unique_ptr (or a reference or pointer), as ReminderService does.
The non-virtual interface idea
Section titled “The non-virtual interface idea”An interface of public virtual functions trusts every implementation to follow the contract. Sometimes the base class should enforce part of it instead, such as checking arguments or counting calls, for every channel, including ones not written yet. The non-virtual interface (NVI) idea does this: the public function is not virtual, and it calls a private virtual function that derived classes override.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A base class that enforces its own rules for every channel. Outside code// calls the public, NON-virtual send; send does the checks and counting and// calls the private virtual deliver for the one step that differs per// channel. A derived class can change only that step, so it can never skip// the checks.class CheckedChannel {public: // Virtual for the same reason as Notifier's: channels may be deleted // through a CheckedChannel pointer. virtual ~CheckedChannel() = default;
// Not virtual: every channel gets the same checks and counting. // Returns false for an empty recipient or text, or if delivery fails. bool send(const Message& message) { // 1. Reject a bad message before any channel sees it. if (message.recipient.empty() || message.text.empty()) return false; // 2. The virtual call: runs the derived class's deliver, for example // LogChannel::deliver below. if (!deliver(message)) return false; // 3. Count only deliveries that succeeded. ++delivered_; return true; } [[nodiscard]] int delivered() const noexcept { return delivered_; }
protected: CheckedChannel() = default; CheckedChannel(const CheckedChannel&) = default; CheckedChannel& operator=(const CheckedChannel&) = default; CheckedChannel(CheckedChannel&&) = default; CheckedChannel& operator=(CheckedChannel&&) = default;
private: // The customization point. Called only with a valid message. Private, so // outside code cannot call it and bypass send; a derived class may still // override a private virtual function, which C++ allows. virtual bool deliver(const Message& message) = 0;
int delivered_ = 0;};
// A channel that "delivers" by writing a line to a list. It supplies only// deliver; the checks and the count come from CheckedChannel::send.class LogChannel final : public CheckedChannel {public: [[nodiscard]] const std::vector<std::string>& lines() const noexcept { return lines_; }
private: // Builds a line such as "ada@example.org: Emma is due" and keeps it. // Always succeeds, because send has already checked the message. bool deliver(const Message& message) override { lines_.push_back(message.recipient + ": " + message.text); return true; }
std::vector<std::string> lines_;};How this code works: a call to LogChannel::send
Take LogChannel log; and the call log.send({"ada", "hi"}).
LogChannelhas nosendof its own, so this isCheckedChannel::send. It is not virtual, so no derived class can replace it.- The recipient
"ada"and the text"hi"are both non-empty, so the first check passes. (With{"", "no recipient"},sendwould returnfalsehere, anddeliverwould never run.) deliver(message)is a virtual call. The object is aLogChannel, soLogChannel::deliverruns and stores the line"ada: hi". It returnstrue.- Back in
CheckedChannel::send,delivered_goes from 0 to 1, andsendreturnstrue.
The order of control is the point: the base class calls the derived class, not the other way round, so the checks in step 2 and the count in step 4 happen for every channel, including channels written later.
CheckedChannel::send rejects an empty recipient or text and counts successful
deliveries. A derived class cannot override send, so every call through a
CheckedChannel& runs the checks. (A derived class could declare its own send,
which hides the base one for calls made on the derived type; do not.)
LogChannel overrides only deliver, which is private: C++ allows overriding a
private virtual function. Outside code cannot call deliver; it is reached only
through send.
Use NVI when the base has real rules to enforce for all implementations. For a
plain interface with nothing to enforce, as Notifier is, public pure virtual
functions are simpler.
Testing through the interface
Section titled “Testing through the interface”Because ReminderService depends only on Notifier, a test can give it a test
double: a class written for the test that implements the interface and records
what happened.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A test double: a Notifier written for the test, which records calls and// answers as told. ReminderService cannot tell it from a real channel.// accept: what every send should answer. calls: where to count the calls,// a pointer to an int the test owns, so the test can read the count after// the service has taken ownership of the fake itself.class FakeNotifier final : public Notifier {public: explicit FakeNotifier(bool accept, int* calls) : accept_(accept), calls_(calls) {} // The parameter has no name because the fake never reads the message. bool send(const Message&) override { ++*calls_; // *calls_ is the test's int; ++ adds one to it return accept_; } std::string_view channel() const noexcept override { return "fake"; }
private: bool accept_; int* calls_; // non-owning; the test's counter outlives the service};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; 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.
// Each channel accepts what it can deliver and refuses the rest. The SMS// text is 161 'x' characters, one more than max_length. Only the first// email was accepted, so the outbox holds exactly one message.LLD_TEST(each_channel_applies_its_own_rules) { EmailNotifier email; SmsNotifier sms; LLD_CHECK(email.send({"ada@example.org", "hi"})); LLD_CHECK(!email.send({"+447700900123", "hi"})); LLD_CHECK(sms.send({"+447700900123", "hi"})); LLD_CHECK(!sms.send({"+447700900123", std::string(SmsNotifier::max_length + 1, 'x')})); LLD_CHECK_EQ(email.outbox().size(), std::size_t{1});}
// Two fakes: the first refuses, the second accepts. The service must ask// the first, move on to the second, stop there, and report "fake". Each// counter ends at 1, proving each channel was asked exactly once. Passing// nullptr (which converts to an empty unique_ptr) must throw.LLD_TEST(the_service_tries_channels_in_order_through_the_interface) { int first_calls = 0; int second_calls = 0; ReminderService service; service.add_channel(std::make_unique<FakeNotifier>(false, &first_calls)); service.add_channel(std::make_unique<FakeNotifier>(true, &second_calls)); LLD_CHECK_EQ(service.remind({"anyone", "hi"}), std::string("fake")); LLD_CHECK_EQ(first_calls, 1); LLD_CHECK_EQ(second_calls, 1); LLD_CHECK_THROWS(service.add_channel(nullptr), std::invalid_argument);}
// LogChannel's deliver accepts anything, so the empty-recipient refusal can// only come from CheckedChannel::send. Only the good message is counted// and logged.LLD_TEST(the_nvi_base_checks_every_channel) { LogChannel log; LLD_CHECK(!log.send({"", "no recipient"})); // rejected before deliver runs LLD_CHECK(log.send({"ada", "hi"})); LLD_CHECK_EQ(log.delivered(), 1); LLD_CHECK_EQ(log.lines().size(), std::size_t{1});}
// static_assert checks a condition while compiling: if it is false, the// file does not build, so these "tests" can never fail at run time. The// std::is_..._v traits from <type_traits> answer yes/no questions about a// type. (Notifier is not copy-constructible for two reasons: its copy// constructor is protected, and an abstract class cannot be created at all.)LLD_TEST(the_interface_cannot_be_copied_or_created_directly) { static_assert(std::is_abstract_v<Notifier>); static_assert(std::has_virtual_destructor_v<Notifier>); static_assert(!std::is_copy_constructible_v<Notifier>); // copying is protected static_assert(std::is_copy_constructible_v<EmailNotifier>); static_assert(std::is_final_v<SmsNotifier>);}The second test checks the service’s own behaviour (try channels in order, stop at
the first success) without sending anything. The last test uses static_assert to
pin down the interface’s design: abstract, virtual destructor, not copyable through
the base, and SmsNotifier final.
When to use inheritance, and when not
Section titled “When to use inheritance, and when not”Use an interface with virtual functions when:
- several implementations of one operation must be chosen at run time (from configuration, user choice, or a list of fallbacks, as here);
- code should depend on what is done, not how, so that implementations can be added or replaced, including by test doubles.
Prefer something else when:
- The set of types is fixed and small, and known when compiling. A
std::variantwithstd::visit, or a plainenumwith aswitch, can be simpler. - The choice is made at compile time. Templates (a later lesson) avoid the run-time cost and allow inlining.
- You only want to reuse code. Inheriting to get access to another class’s functions couples the classes tightly. The next lesson explains why composition is usually better.
Virtual calls have a small run-time cost (an indirect call, and usually no
inlining). It rarely matters next to the work a function like send does, but it
can in a tight inner loop.
Common mistakes
Section titled “Common mistakes”- Forgetting the virtual destructor on a class used through base pointers.
- Forgetting
override. A small signature mismatch silently creates a new function instead of replacing the base one. - Storing polymorphic objects by value, in variables or containers. They are sliced.
- Deriving from a class not designed as a base, such as a standard container or a plain record, to reuse its members.
- Calling a virtual function from a constructor or destructor. While the base part is being constructed or destroyed, the derived part does not exist, so the base’s version runs (or, for a pure virtual function, the behaviour is undefined).
- Deep hierarchies. Each level adds rules every subclass must know. Keep hierarchies shallow: usually one interface and its implementations.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Every reminder must be logged, whichever channel sends it.”
There are three places this could go. Putting the logging in each channel
duplicates it and relies on future channels remembering. Putting it in
ReminderService::remind works if the service is the only caller, and is the
simplest change. If channels are used from other places too, the NVI shape fits:
move Notifier to a public non-virtual send that logs and calls a private
virtual deliver, as CheckedChannel does. That changes every implementation’s
override from send to deliver, which override makes the compiler check. A
fourth option, a wrapper class that implements Notifier and forwards to another
Notifier, appears in the patterns section as the Decorator pattern.
Exercise: Find the slicing and destructor bugs
This code compiles, given the usual standard headers. (With -Wall, GCC 11 warns about one of the bugs and Clang 14
about two; without warnings enabled, neither says anything.) Find three bugs, say
what goes wrong at run time, and fix each.
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
class Fine {public: explicit Fine(int amount) : amount_(amount) {} virtual int amount() const { return amount_; }private: int amount_;};
class LateFine : public Fine {public: LateFine(int amount, int days) : Fine(amount), days_(days) {} // Fine::amount() calls the base class's version by name, not the // virtual one, so this does not call itself. int amount() const override { return Fine::amount() * days_; }private: int days_;};
class WaivedFine : public Fine {public: using Fine::Fine; // inherit Fine's constructors: WaivedFine(int amount) int amount() { return 0; } // waived fines cost nothing};
// Adds up the amounts of all the fines it is given.int total(std::vector<Fine> fines) { int sum = 0; for (const Fine& fine : fines) sum += fine.amount(); return sum;}
// Records a fine, then deletes it.void record(Fine* fine) { // ... store it in a log ... delete fine;}Show the explained answer
- Slicing in
total.std::vector<Fine>storesFinevalues, so aLateFineadded to it loses itsdays_and its override: every fine counts at its base amount. Fix: takeconst std::vector<std::unique_ptr<Fine>>&(or a vector ofconst Fine*if the fines are owned elsewhere), and prevent the mistake by makingFine’s copy operationsprotected. - No virtual destructor.
Finehas virtual functions but no virtual destructor, sodelete fineon aLateFinehas undefined behaviour. Fix: addvirtual ~Fine() = default;(and then decide the copy and move operations, as in the Rule of Zero and Rule of Five lesson). GCC and Clang both warn about thisdeletewith-Wall. WaivedFine::amountdoes not override. It is missingconst, so it declares a new, unrelated function. Through aFine&,amount()still returns the base amount, so waived fines are charged. Fix:int amount() const override { return 0; }; withoverride, the original mistake would have been a compile error. (Clang 14 warns about it with-Wall, through-Woverloaded-virtual; GCC 11 does not.)
A design point as well: record takes a raw Fine* and deletes it, so ownership
is invisible in its signature. Take std::unique_ptr<Fine> to say it takes
ownership.
Summary
Section titled “Summary”- An interface is a class of pure virtual functions; code that depends on it works with any implementation, including test doubles.
virtualdispatches on the object’s real type;overridemakes the compiler check that a function really replaces a base one;finalforbids further overriding or deriving.- A class used through base pointers needs a public virtual destructor; a class not designed as a base should not be derived from.
- Hold polymorphic objects through pointers or references, and make slicing impossible with an abstract base and protected copy operations.
- The non-virtual interface idea lets a base class enforce rules for every implementation.