计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 2 · 本科二年级

3Inheritance and Polymorphism

The town library fines late borrowers, and not every item is fined alike. Ordinary books cost 10 cents a day, at most 5.00; comics, always in demand, 25 cents a day, at most 3.00; study books get three days of grace, then 20 cents a day with no ceiling. In C the natural program gives each item a kind tag and switches on it.

enum kind { STANDARD, COMIC, STUDY };

struct item {
    const char *title;
    enum kind kind;
};

int fine_cents(const struct item *it, int days_late)    // fine for one late loan
{
    if (days_late <= 0)
        return 0;
    switch (it->kind) {
    case STANDARD:                                      // 10 cents a day, at most 5.00
        return days_late * 10 < 500 ? days_late * 10 : 500;
    case COMIC:                                         // 25 cents a day, at most 3.00
        return days_late * 25 < 300 ? days_late * 25 : 300;
    case STUDY:                                         // 3 days of grace, then 20 a day
        return days_late > 3 ? (days_late - 3) * 20 : 0;
    }
    return 0;
}

const char *kind_name(enum kind k)                      // a second switch on the same tag
{
    switch (k) {
    case STANDARD: return "standard";
    case COMIC:    return "comic";
    case STUDY:    return "study";
    }
    return "?";
}
Listing 3.1. Fines by a switch on a kind tag code/bachelor-2/03-cpp-polymorphism/listings/fines_switch.c
$ gcc -std=c17 -O2 -Wall -Wextra -o fines_switch fines_switch.c -lm && ./fines_switch
The Silent Code        standard    2 days:  0.20  10 days:  1.00  60 days:  5.00
A Year by the Island   comic       2 days:  0.50  10 days:  2.50  60 days:  3.00
Tides and Moons        study       2 days:  0.00  10 days:  1.40  60 days: 11.40
Output 3.1. Three items, three rules, three lateness values.

The program is correct, and it does not age well. Every function that depends on the kind repeats the switch: here two of them, in a real system dozens (the loan period, the shelf, the label, the reminder letter). When the library starts lending maps, someone must find every switch and add a case to each, and the compiler warns only for some of the switches it can see. This chapter gives each kind its own class and lets the call itself choose the code of the right kind: adding a kind then means adding a class, in a new file, and editing nothing that works.

You already know

A class (Chapter 1) bundles data with the functions that use them, with an invariant kept by its constructor and members. The school volumes met inheritance, in Python: a class can be declared as a special case of another and inherit its methods. In C, a pointer to a function (Book 3) holds the address of a function, and a call through it runs whichever function it points to: the choice is made at run time. Objects are copied and moved by the rules of Chapter 2.

3.1 Derived classes

Definition 3.1 (Base class, derived class, inheritance)

A class D declared as class D : public B is a derived class of the base class B. Every D object contains a B object (its base part) followed by the members D declares, and D has every member function of B. This is inheritance. A D can be used wherever a B is expected: a D * converts to a B * and a D binds to a B &, both pointing at the base part.

Access gains a third level. A public member is visible to everyone, a private one only to the class’s own members, and a protected one to the class’s members and to those of the classes derived from it. Since a derived object contains a base object, building one runs two constructors.

struct Part {
    std::string s;
    explicit Part(std::string x) : s(std::move(x))
        { std::printf("  make member %s\n", s.c_str()); }
    ~Part() { std::printf("  drop member %s\n", s.c_str()); }
};

struct Item {
    Part code{"code"};
    Item() { std::printf("  Item body\n"); }
    ~Item() { std::printf("  ~Item body\n"); }
};

struct Map : Item {                      // a Map is an Item, with one more member
    Part sheet{"sheet"};
    Map() { std::printf("  Map body\n"); }
    ~Map() { std::printf("  ~Map body\n"); }
};

int main()
{
    std::puts("make a Map:");
    {
        Map m;
        std::puts("drop it:");
    }
    return 0;
}
Listing 3.2. A Map is an Item code/bachelor-2/03-cpp-polymorphism/listings/ctor_order.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra -o ctor_order ctor_order.cpp && ./ctor_order
make a Map:
  make member code
  Item body
  make member sheet
  Map body
drop it:
  ~Map body
  drop member sheet
  ~Item body
  drop member code
Output 3.2. Base first on the way in, last on the way out.

The order is fixed by the language: the base part is constructed first (its members, then its constructor’s body), then the derived class’s members in order of declaration, then its body; destruction runs the same steps in reverse. When a derived constructor’s body starts, its base part is complete and may be used; when a base destructor’s body runs, the derived part is already gone. A derived constructor passes arguments to the base constructor in its initialiser list, as Recording(...) : Item(std::move(t)) does below.

The rule “a D can be used where a B is expected” has a trap when the B is an object rather than a reference or a pointer. A B object has room for a B and nothing more.

Definition 3.2 (Object slicing)

Object slicing is the copy of a derived object into an object of its base class: by assignment, by initialisation, or by passing it by value to a parameter of the base type. Only the base part is copied, and the result is a plain base object; the derived members and the derived behaviour are lost.

class Item {
public:
    explicit Item(std::string t) : title_(std::move(t)) {}
    virtual ~Item() = default;
    virtual std::string label() const { return title_; }

protected:
    std::string title_;
};

class Recording : public Item {
public:
    Recording(std::string t, int minutes) : Item(std::move(t)), minutes_(minutes) {}
    std::string label() const override
        { return title_ + " (" + std::to_string(minutes_) + " min)"; }

private:
    int minutes_;
};

void by_value(Item it) { std::printf("by value:     %s\n", it.label().c_str()); }
void by_reference(const Item &it) { std::printf("by reference: %s\n", it.label().c_str()); }

int main()
{
    Recording r("Harbour Songs", 42);
    by_reference(r);
    by_value(r);                      // the parameter is an Item built from the Item part of r
    Item copy = r;                     // the same slicing
    std::printf("copy:         %s\n", copy.label().c_str());
    std::printf("sizeof(Item) = %zu, sizeof(Recording) = %zu\n",
        sizeof(Item), sizeof(Recording));
    return 0;
}
Listing 3.3. A recording passed by reference and by value code/bachelor-2/03-cpp-polymorphism/listings/slicing.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra -o slicing slicing.cpp && ./slicing
by reference: Harbour Songs (42 min)
by value:     Harbour Songs
copy:         Harbour Songs
sizeof(Item) = 40, sizeof(Recording) = 48
Output 3.3. By value, the recording lost its minutes.
Slicing. Copying a Recording into an Item copies the base part only. The copy is a genuine Item, whose table pointer () is that of Item, so even its virtual calls run Item’s functions.
Slicing. Copying a Recording into an Item copies the base part only. The copy is a genuine Item, whose table pointer (Section 3.2) is that of Item, so even its virtual calls run Item’s functions.

3.2 Virtual functions

Definition 3.3 (Virtual function, override)

A member function declared virtual in a base class is a virtual function. A derived class overrides it by declaring a function with the same name and parameters; the keyword override asks the compiler to check that there is something to override, and final forbids further overriding. A function that is not virtual can only be hidden by a derived function of the same name, which is a different thing.

Definition 3.4 (Dynamic dispatch, subtype polymorphism)

A call of a virtual function through a pointer or a reference runs the version of the class of the object pointed at, which is known only at run time, not the version of the pointer’s type: this is dynamic dispatch. Code written against a base class and able to work, through dynamic dispatch, with objects of every derived class has subtype polymorphism.

The shapes below share one base class. area has no sensible default and is declared = 0 (the next section explains); name has one; describe is an ordinary function written once in the base class, whose calls to name and area are dispatched.

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;                 // every shape has one; no default
    virtual const char *name() const { return "shape"; }
    void describe() const { std::printf("%-9s area %8.2f\n", name(), area()); }
};

class Circle : public Shape {
public:
    explicit Circle(double r) : r_(r) {}
    double area() const override { return 3.14159265358979 * r_ * r_; }
    const char *name() const override { return "circle"; }

private:
    double r_;
};

class Rectangle : public Shape {
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    double area() const override { return w_ * h_; }
    const char *name() const override { return "rectangle"; }

protected:                                         // visible to classes derived from Rectangle
    double w_, h_;
};
Listing 3.4. A base class and two derived classes code/bachelor-2/03-cpp-polymorphism/listings/shapes.hpp
int main()
{
    std::vector<std::unique_ptr<Shape>> plan;        // the plot plan of a garden
    plan.push_back(std::make_unique<Rectangle>(12.0, 8.5));
    plan.push_back(std::make_unique<Circle>(2.5));
    plan.push_back(std::make_unique<Rectangle>(3.0, 3.0));
    double total = 0;
    for (const auto &s : plan) {
        s->describe();                               // area() and name() of the real class
        total += s->area();
    }
    std::printf("total     area %8.2f\n", total);
    return 0;
}
Listing 3.5. A plan of shapes, each called through Shape code/bachelor-2/03-cpp-polymorphism/listings/shapes.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra -o shapes shapes.cpp && ./shapes
rectangle area   102.00
circle    area    19.63
rectangle area     9.00
total     area   130.63
Output 3.4. Each call ran the function of the real class.

The loop sees only const Shape &, yet each describe printed the right name and area. Destroying the objects through the base class needs one more virtual function. When delete is applied to a B * that points at a D, the destructor called is B’s unless B’s destructor is virtual, and the behaviour is undefined.

struct Item {
    ~Item() { std::puts("~Item"); }              // not virtual
    int id = 0;
};

struct Recording : Item {
    ~Recording() { std::puts("~Recording"); }
    std::string tracks[4] = {"intro", "harbour", "tide", "coda"};
};

int main()
{
    std::setvbuf(stdout, nullptr, _IONBF, 0);   // unbuffered: the report ends the program
    Item *it = new Recording;
    delete it;                                   // undefined behaviour
    return 0;
}
Listing 3.6. A derived object deleted through its base code/bachelor-2/03-cpp-polymorphism/listings/no_virtual_dtor.cpp
$ g++ -std=c++20 -O0 -g -fsanitize=address -o no_virtual_dtor no_virtual_dtor.cpp && ./no_virtual_dtor
~Item
=================================================================
==1000==ERROR: AddressSanitizer: new-delete-type-mismatch on 0x50d000000040 in thread T0:
  object passed to delete has wrong type:
  size of the allocated type:   136 bytes;
  size of the deallocated type: 4 bytes.
    #2 0x7ffff6c29d8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f)
Output 3.5. AddressSanitizer: the size freed is not the size allocated. Some lines are left out.

Only ~Item ran: the four strings of the recording were never destroyed, and delete returned the block as if it held a 4-byte Item when 136 bytes had been allocated. The rule follows: a class meant to be used through base pointers declares virtual ~B() = default;, as Shape does. A std::unique_ptr<B> does not help, since it calls the same delete (Exercise 3.2).

How does a call find the right function at run time? The compiler gives every class with virtual functions one table of function addresses, and every object of such a class one hidden pointer to the table of its class, set by the constructor. The same mechanism can be written by hand in C.

Definition 3.5 (Dispatch table, table pointer)

The dispatch table (or vtable) of a class with virtual functions is an array, one per class and built by the compiler, of the addresses of the versions of its virtual functions that apply to that class. Each object of the class holds a table pointer to its class’s table. A virtual call loads the table pointer from the object, loads the address from a fixed position in the table, and calls it.

struct shape;
struct shape_table {                         // one table per class
    double (*area)(const struct shape *);
    const char *(*name)(const struct shape *);
};
struct shape {
    const struct shape_table *table;        // one pointer per object, set by the "constructor"
};
struct circle { struct shape base; double r; };
struct rect { struct shape base; double w, h; };

static double circle_area(const struct shape *s)
{
    const struct circle *c = (const struct circle *)s;   // base is the first member
    return 3.14159265358979 * c->r * c->r;
}
static const char *circle_name(const struct shape *s) { (void)s; return "circle"; }
static double rect_area(const struct shape *s)
{
    const struct rect *r = (const struct rect *)s;
    return r->w * r->h;
}
static const char *rect_name(const struct shape *s) { (void)s; return "rectangle"; }

static const struct shape_table CIRCLE_TABLE = {circle_area, circle_name};
static const struct shape_table RECT_TABLE = {rect_area, rect_name};

int main(void)
{
    struct rect bed = {{&RECT_TABLE}, 12.0, 8.5};
    struct circle pond = {{&CIRCLE_TABLE}, 2.5};
    struct shape *plan[] = {&bed.base, &pond.base};
    for (int i = 0; i < 2; i++) {
        const struct shape *s = plan[i];
        printf("%-9s area %8.2f\n", s->table->name(s), s->table->area(s));  // 2 loads, 1 call
    }
    return 0;
}
Listing 3.7. Dispatch tables written in C code/bachelor-2/03-cpp-polymorphism/listings/vtable_by_hand.c
$ gcc -std=c17 -O2 -Wall -Wextra -o vtable_by_hand vtable_by_hand.c -lm && ./vtable_by_hand
rectangle area   102.00
circle    area    19.63
Output 3.6. The first two lines of the output of Listing 3.5, by hand.
The two objects of , of two classes. A call s->table->area(s), or its C++ form s->area(), follows the object’s table pointer to its class’s table, takes the address at the position reserved for area, and calls that function with the object.
The two objects of Listing 3.7, of two classes. A call s->table->area(s), or its C++ form s->area(), follows the object’s table pointer to its class’s table, takes the address at the position reserved for area, and calls that function with the object.

Proposition 3.6 (Cost of dispatch tables)

In this scheme, a program with kk classes that have virtual functions holds kk tables, the table of a class having one entry per virtual function of the class, and each object of these classes holds exactly one table pointer, whatever the number of virtual functions. A virtual call costs two loads (the table pointer and the address) and an indirect call, independently of the number of classes.

Proof. The tables depend on the class only: all objects of one class call the same versions, so one table per class suffices, with one slot per virtual function, a derived class’s table extending its base’s with the same positions for the inherited functions so that a call compiled against the base finds the right slot. An object needs only to say which class it is of, and one pointer to that class’s table says it, whatever the table’s length. The call sequence of Definition 3.5 reads the object’s pointer and one slot at a position fixed at compile time, then calls; nothing in it depends on how many classes exist. ∎

struct Plain { int id; };
struct OneVirtual { virtual ~OneVirtual() = default; int id; };
struct ManyVirtual {
    virtual ~ManyVirtual() = default;
    virtual void a() {}
    virtual void b() {}
    virtual void c() {}
    int id;
};
struct Derived : ManyVirtual { void a() override {} int extra; };

int main()
{
    std::printf("pointer      %2zu bytes\n", sizeof(void *));
    std::printf("Plain        %2zu bytes\n", sizeof(Plain));
    std::printf("OneVirtual   %2zu bytes\n", sizeof(OneVirtual));
    std::printf("ManyVirtual  %2zu bytes\n", sizeof(ManyVirtual));
    std::printf("Derived      %2zu bytes\n", sizeof(Derived));
    ManyVirtual x, y;
    Derived d;
    // the table pointer is the first 8 bytes of each object (an implementation detail)
    auto table = [](const void *obj) { return *static_cast<void *const *>(obj); };
    std::printf("x and y share a table: %s; d has another: %s\n",
                table(&x) == table(&y) ? "yes" : "no", table(&x) != table(&d) ? "yes" : "no");
    return 0;
}
Listing 3.8. Sizes of objects with and without virtual functions code/bachelor-2/03-cpp-polymorphism/listings/sizes.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra -o sizes sizes.cpp && ./sizes
pointer       8 bytes
Plain         4 bytes
OneVirtual   16 bytes
ManyVirtual  16 bytes
Derived      16 bytes
x and y share a table: yes; d has another: yes
Output 3.7. One table pointer, whatever the number of virtual functions.

The C++ standard does not prescribe tables, but every major compiler uses them, with the table pointer at the start of the object, as the last line of the output shows. On this 64-bit machine a pointer is 8 bytes: Plain is its int; OneVirtual and ManyVirtual are a pointer plus an int, padded to a multiple of 8; and Derived’s extra int fits in that padding (Exercise 3.4).

3.3 Abstract classes

Definition 3.7 (Pure virtual function, abstract class)

A virtual function declared with = 0, as virtual double area() const = 0;, is a pure virtual function: it has no version in its class, and every derived class that is to be instantiated must override it. A class with at least one pure virtual function, declared or inherited and not overridden, is an abstract class: no object of it can be created, only objects of derived classes that override every pure function.

An abstract class with only pure virtual functions and a virtual destructor describes what its derived classes provide and nothing of how. It plays the role an interface plays in other languages, and code written against it can be compiled before any of its implementations exists. Shape is such a class but for describe and name, which every shape shares.

One question remains: which version runs when a constructor calls a virtual function? While the base constructor runs, the derived members have not been built yet (Output 3.2); calling a derived version would read them uninitialised. C++ therefore treats the object, during the base constructor and the base destructor, as an object of the base class: virtual calls made there run the base versions (Exercise 3.5). In terms of tables, each constructor sets the table pointer to its own class’s table on entry, so the pointer is the base’s while the base constructor runs.

3.4 Designing with classes

Inheritance says “a D is a B”: every D can stand in for a B. It is often used where a weaker relation is meant.

Definition 3.8 (Composition)

A class uses composition when it holds an object of another class as a member (“has a”) and calls it, rather than deriving from it (“is a”). A member may be held by value, or by reference or pointer to an object of an abstract class, in which case the behaviour it provides can be chosen at run time.

A car has an engine and is not one; a loan has a fine policy. Composition exposes only what the class chooses to forward, whereas a derived class inherits the whole public interface of its base, along with every promise the base makes. Those promises are what inheritance must keep.

Definition 3.9 (Substitution principle)

A derived class D of B satisfies the substitution principle if every property that a client can prove about objects of B from the specification of B (the preconditions and postconditions of its functions, and its invariant) also holds for objects of D. Equivalently, a correct client of B stays correct when given a D. The principle bears the name of Barbara Liskov, who stated it in a keynote in 1987 and, with Jeannette Wing, as a definition of subtyping in 1994.

Geometry says that a square is a rectangle. Here is what happens when a class Square derives from a class Rectangle whose setters promise to change one side only.

Example 3.10 (A square that is not a rectangle)

class Rectangle {
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    virtual ~Rectangle() = default;
    virtual void set_width(double w) { w_ = w; }    // postcondition: width w, height unchanged
    virtual void set_height(double h) { h_ = h; }   // postcondition: height h, width unchanged
    double area() const { return w_ * h_; }

protected:
    double w_, h_;
};

class Square : public Rectangle {                    // keeps its sides equal
public:
    explicit Square(double s) : Rectangle(s, s) {}
    void set_width(double w) override { w_ = h_ = w; }
    void set_height(double h) override { w_ = h_ = h; }
};

// A client written against Rectangle: resize a plot to 4 m by 5 m.
bool resize_plot(Rectangle &r)
{
    r.set_width(4);
    r.set_height(5);
    return r.area() == 20;                           // what the postconditions promise
}

int main()
{
    Rectangle r(2, 3);
    Square s(3);
    bool ok_r = resize_plot(r), ok_s = resize_plot(s);
    std::printf("rectangle: %s (area %g)\n", ok_r ? "as promised" : "broken", r.area());
    std::printf("square:    %s (area %g)\n", ok_s ? "as promised" : "broken", s.area());
    return 0;
}
Listing 3.9. A client of Rectangle given a Square code/bachelor-2/03-cpp-polymorphism/listings/square.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra -o square square.cpp && ./square
rectangle: as promised (area 20)
square:    broken (area 25)
Output 3.8. The client’s promise holds for one of the two.

resize_plot relies on the postconditions of Rectangle: after set_width(4) and set_height(5) the area is 20. Square must keep its sides equal, so its set_height(5) also changes the width, and the client sees 25. The square of geometry is a rectangle because a geometric rectangle never changes; a mutable Square cannot keep the promises of a mutable Rectangle, whichever way it overrides the setters (Exercise 3.8). Either the two classes have no setters, or Square is not derived from Rectangle.

The library’s fines are the case where inheritance fits. A policy is a function of the days late, and every policy can stand in for every other: a loan asks its policy for a fine and accepts any answer. The policies form an abstract class and three derived ones; the loan, or here the function that sums the fines, holds a policy by composition. The rule that maps a book to its policy is written once, in policy_for.

class FinePolicy {                              // an abstract class: the interface of a policy
public:
    virtual ~FinePolicy() = default;
    virtual int fine_cents(int days_late) const = 0;
    virtual std::string name() const = 0;
};

class StandardFine : public FinePolicy {            // 10 cents a day, at most 5.00
public:
    int fine_cents(int d) const override { return d * 10 < 500 ? d * 10 : 500; }
    std::string name() const override { return "standard"; }
};

class ComicFine : public FinePolicy {               // 25 cents a day, at most 3.00
public:
    int fine_cents(int d) const override { return d * 25 < 300 ? d * 25 : 300; }
    std::string name() const override { return "comic"; }
};

class StudyFine : public FinePolicy {               // 3 days of grace, then 20 cents a day
public:
    int fine_cents(int d) const override { return d > 3 ? (d - 3) * 20 : 0; }
    std::string name() const override { return "study"; }
};

const FinePolicy &policy_for(const Book &b)         // the only place that knows the genres
{
    static const StandardFine standard;
    static const ComicFine comic;
    static const StudyFine study;
    if (b.genre == "comics")
        return comic;
    if (b.genre == "science" || b.genre == "history")
        return study;
    return standard;
}
Listing 3.10. The fine policies, and the only function that knows the genres code/bachelor-2/03-cpp-polymorphism/listings/library.hpp

The rest of library.hpp reads books.csv and loans.csv of the town (the book’s genre, and each loan’s dates; a loan not yet returned has an empty return date) and counts the days late at the end of 2025. The program below sums the fines.

    auto books = read_books(argv[1]);
    auto loans = read_loans(argv[2]);
    int today = day_number("2025-12-31");
    std::map<std::string, std::pair<int, int>> per_policy;     // name -> (late loans, cents)
    std::vector<std::pair<int, int>> fines;                    // (cents, loan id)
    for (const Loan &l : loans) {
        int d = days_late(l, today);
        if (d == 0)
            continue;
        const FinePolicy &p = policy_for(books.at(l.book_id)); // dynamic dispatch from here on
        int c = p.fine_cents(d);
        per_policy[p.name()].first++;
        per_policy[p.name()].second += c;
        fines.push_back({c, l.id});
    }
    std::printf("%zu loans, %zu late\n", loans.size(), fines.size());
Listing 3.11. Fines on all the town’s loans; the call p.fine_cents(d) is dispatched code/bachelor-2/03-cpp-polymorphism/listings/library_demo.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra library_demo.cpp -o library_demo
$ ./library_demo books.csv loans.csv
400 loans, 109 late
  comic      19 late loans,   51.75 owed
  standard   58 late loans,  114.10 owed
  study      32 late loans,  297.60 owed
  largest: loan 27, 62.40
  largest: loan 103, 48.80
  largest: loan 172, 38.20
Output 3.9. The fines owed on 31 December 2025.
The design of the fines. The code that sums fines holds a policy (composition) and knows only the abstract class; the three policies derive from it (inheritance). A fourth policy, for maps, is one more class in one more file, plus one line in policy_for.
The design of the fines. The code that sums fines holds a policy (composition) and knows only the abstract class; the three policies derive from it (inheritance). A fourth policy, for maps, is one more class in one more file, plus one line in policy_for.

Method 3.11 (Adding a kind without editing working code)

To make a family of kinds open to new members:

  1. collect what every kind must provide into an abstract class of pure virtual functions, with a virtual destructor;
  2. write each kind as a derived class, in a file of its own, overriding every pure function;
  3. write the code that uses the kinds against references or pointers to the abstract class only, so that it compiles without seeing any derived class;
  4. create the objects in one place (here policy_for), the only code that names the derived classes.

A new kind is then one new file and one new line in the creating function; no switch has to be found, and the code of step 3 is neither edited nor recompiled. This is the open–closed rule: open to extension, closed to modification.

The price is a virtual call where the switch had a jump. The program below compares a direct call that the compiler may not inline, a virtual call on objects of one class, the same on a random mix of two classes, and a switch on a tag that the compiler inlined, ten million calls each.

struct Shape { virtual ~Shape() = default; virtual double area() const = 0; };
struct Sq : Shape { double s; explicit Sq(double x) : s(x) {} double area() const override { return s * s; } };
struct Ci : Shape { double r; explicit Ci(double x) : r(x) {} double area() const override { return 3.14159 * r * r; } };
struct Tagged { int kind; double x; };          // the C way: a tag and a switch

__attribute__((noinline)) double area_sq(const Sq &q) { return q.s * q.s; }
double area_tagged(const Tagged &t)
{
    switch (t.kind) {
    case 0: return t.x * t.x;
    default: return 3.14159 * t.x * t.x;
    }
}
    double d = ns_per([&] { double s = 0; for (const auto &q : squares) s += area_sq(q); return s; }, n);
    double u = ns_per([&] { double s = 0; for (const auto &p : same) s += p->area(); return s; }, n);
    double v = ns_per([&] { double s = 0; for (const auto &p : shapes) s += p->area(); return s; }, n);
    double w = ns_per([&] { double s = 0; for (const auto &t : tagged) s += area_tagged(t); return s; }, n);
Listing 3.12. Four ways to call an area function (ns_per returns the time of its argument divided by n) code/bachelor-2/03-cpp-polymorphism/listings/dispatch_cost.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra -o dispatch_cost dispatch_cost.cpp && ./dispatch_cost
direct call (not inlined)   1.94 ns
virtual call, one kind      3.45 ns
virtual call, mixed kinds   7.56 ns
switch on a tag, inlined    3.64 ns
Output 3.10. One run on the author’s laptop; the digits change from run to run.

Every line costs a few nanoseconds. The virtual calls cost more than the direct one for two reasons besides the two loads: each object sits in its own heap block reached through a unique_ptr, where the direct call walks one contiguous array; and with mixed kinds the processor cannot guess which function comes next, a cost that Chapter 11 explains. For a fine computed once per loan none of this matters; in an inner loop over millions of small objects it can, and the switch or a template (Chapter 4) is then the better tool.

History — Simula

Classes, inheritance and dispatch on the class of an object come from Simula 67, a language designed by Ole-Johan Dahl and Kristen Nygaard to write simulations, whose objects were the people and machines being simulated. Its designers told the history of the language at the first conference on the history of programming languages, in 1978. C++ was created to write systems programs in the style Simula encouraged, with the efficiency of C.

3.5 Exercises

Exercise 3.1 ★

Predict the four lines printed. For each call, say whether it is dispatched at run time and why.

struct Item {
    virtual ~Item() = default;
    virtual const char *kind() const { return "item"; }
    const char *shelf() const { return "general shelf"; }      // not virtual
};
struct Map : Item {
    const char *kind() const override { return "map"; }
    const char *shelf() const { return "map drawer"; }          // hides Item::shelf
};

void through_pointer(const Item *p)
    { std::printf("pointer:   %s, %s\n", p->kind(), p->shelf()); }
void through_ref(const Item &r) { std::printf("reference: %s, %s\n", r.kind(), r.shelf()); }
void through_value(Item v) { std::printf("value:     %s, %s\n", v.kind(), v.shelf()); }

int main()
{
    Map m;
    through_pointer(&m);
    through_ref(m);
    through_value(m);
    std::printf("direct:    %s, %s\n", m.kind(), m.shelf());
    return 0;
}
Listing 3.13. Pointer, reference, value code/bachelor-2/03-cpp-polymorphism/listings/exo_which.cpp
Solution

Solution of Exercise 3.1.

$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_which exo_which.cpp && ./exo_which
pointer:   map, general shelf
reference: map, general shelf
value:     item, general shelf
direct:    map, map drawer
Output 3.13. The four lines.

kind is virtual: through the pointer and the reference it is dispatched to Map::kind. shelf is not virtual: through an Item * or Item & the compiler calls Item::shelf, chosen at compile time from the static type; Map::shelf only hides it, and is called when the static type is Map, as in the last line. By value, the parameter is a sliced Item: both calls run Item’s versions.

Exercise 3.2 ★

This program owns its sensors with std::unique_ptr, so nothing should go wrong; yet AddressSanitizer stops it at the end of main. Explain the report and fix the program with one word.

struct Sensor {
    ~Sensor() {}
    int id = 0;
};
struct LoggingSensor : Sensor {
    std::vector<double> history = std::vector<double>(1000, 0.0);
};

int main()
{
    std::vector<std::unique_ptr<Sensor>> sensors;
    sensors.push_back(std::make_unique<Sensor>());
    sensors.push_back(std::make_unique<LoggingSensor>());
    std::printf("%zu sensors\n", sensors.size());
    std::fflush(stdout);
    return 0;
}
Listing 3.14. Two sensors code/bachelor-2/03-cpp-polymorphism/listings/exo_owner.cpp
$ g++ -std=c++20 -O0 -g -fsanitize=address -o exo_owner exo_owner.cpp && ./exo_owner
2 sensors
=================================================================
==1000==ERROR: AddressSanitizer: new-delete-type-mismatch on 0x503000000040 in thread T0:
  object passed to delete has wrong type:
  size of the allocated type:   32 bytes;
  size of the deallocated type: 4 bytes.
Output 3.11. The start of the report. Some lines are left out.
Solution

Solution of Exercise 3.2.

std::unique_ptr<Sensor> destroys its object with delete on a Sensor *. Sensor’s destructor is not virtual, so for the LoggingSensor only ~Sensor runs (the vector of 1000 readings is never destroyed) and the block is returned with the size of a Sensor, 4 bytes, instead of the 32 allocated: undefined behaviour, which the sanitizer reports as a type mismatch, from inside unique_ptr’s destructor. The fix is the word virtual: virtual ~Sensor() {}. (A std::shared_ptr<Sensor> made by make_shared<LoggingSensor> would happen to work, because it remembers the real type; relying on that is fragile.)

Exercise 3.3 ★

Add a class Triangle, given its three sides, to the shapes of Listing 3.4, in a new file and without editing shapes.hpp or shapes.cpp’s loop. Its constructor must refuse three lengths that are not the sides of a (non-flat) triangle. Which step of Method 3.11 does each part of your file follow?

Solution

Solution of Exercise 3.3.

class Triangle : public Shape {
public:
    Triangle(double a, double b, double c) : a_(a), b_(b), c_(c)
    {
        if (a <= 0 || b <= 0 || c <= 0 || a + b <= c || a + c <= b || b + c <= a)
            throw std::invalid_argument("not a triangle");
    }
    double area() const override                    // Heron's formula
    {
        double s = (a_ + b_ + c_) / 2;
        return std::sqrt(s * (s - a_) * (s - b_) * (s - c_));
    }
    const char *name() const override { return "triangle"; }

private:
    double a_, b_, c_;
};
Triangle, in its own file code/bachelor-2/03-cpp-polymorphism/exercises/triangle.hpp

Step 1 is already done by Shape; the file is step 2: one derived class, overriding the pure area (by Heron’s formula) and name. The loop of shapes.cpp is step 3 and is untouched; only the place that creates the shapes (step 4) gains a line, a push_back of std::make_unique<Triangle>(3, 4, 5). The strict inequalities refuse flat triangles, whose area would be 0. Tested in tests/shapes_test.cpp.

Exercise 3.4 ★

On this machine int is 4 bytes and aligned on 4, a pointer 8 bytes and aligned on 8, and an object’s size is a multiple of its strictest member alignment. Explain each size of Output 3.7. What would sizeof print for a class with a table pointer and three char members? For a class with two double members and five virtual functions?

Solution

Solution of Exercise 3.4.

Plain: one int, 4 bytes. OneVirtual: table pointer (8) and int (4) make 12, rounded up to 16, a multiple of the pointer’s alignment 8. ManyVirtual: the same 16, since four virtual functions still mean one pointer (Proposition 3.6). Derived: its int goes into the 4 bytes of padding at the end of the base part, which this compiler’s rules allow for a base class with virtual functions, so it stays 16. A table pointer and three char: 8+3=118 + 3 = 11, rounded to 16. Two double and five virtual functions: 8+16=248 + 16 = 24, already a multiple of 8.

Exercise 3.5 ★★

Predict the output, line by line. Why does the constructor of Item not print a map of the coast? Which would be worse if it did?

struct Item {
    Item() { std::printf("Item(): %s\n", describe().c_str()); }
    virtual ~Item() { std::printf("~Item(): %s\n", describe().c_str()); }
    virtual std::string describe() const { return "an item"; }
    void show() const { std::printf("show(): %s\n", describe().c_str()); }
};
struct Map : Item {
    std::string region = "the coast";
    Map() { std::printf("Map(): %s\n", describe().c_str()); }
    std::string describe() const override { return "a map of " + region; }
};

int main()
{
    Map m;
    m.show();
    return 0;
}
Listing 3.15. A virtual call in a constructor and a destructor code/bachelor-2/03-cpp-polymorphism/listings/exo_ctor_virtual.cpp
Solution

Solution of Exercise 3.5.

$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_ctor_virtual exo_ctor_virtual.cpp && ./exo_ctor_virtual
Item(): an item
Map(): a map of the coast
show(): a map of the coast
~Item(): an item
Output 3.14. The four lines.

While Item’s constructor runs, the object is an Item: its table pointer is Item’s and the call runs Item::describe. Then Map’s constructor sets the table pointer to Map’s, builds region, and its call runs Map::describe; so does show. When m dies, ~Map (implicit) runs first, then ~Item, during which the object is an Item again. If the base constructor called Map::describe, it would read region before its constructor ran: a string not yet built, which is undefined behaviour and in practice a crash or garbage.

Exercise 3.6 ★★

The catalogue below prints Harbour Songs without its minutes. Explain why, then fix it so that the catalogue holds books and recordings and prints each with its own label. Which owner type did you choose for the elements, and why not std::vector<Item &>?

struct Item {
    std::string title;
    virtual ~Item() = default;
    virtual std::string label() const { return title; }
};
struct Recording : Item {
    int minutes = 0;
    std::string label() const override
        { return title + " (" + std::to_string(minutes) + " min)"; }
};

int main()
{
    std::vector<Item> catalogue;
    Recording r;
    r.title = "Harbour Songs";
    r.minutes = 42;
    catalogue.push_back(r);
    Item book;
    book.title = "The Silent Code";
    catalogue.push_back(book);
    for (const Item &it : catalogue)
        std::printf("%s\n", it.label().c_str());
    return 0;
}
Listing 3.16. A catalogue code/bachelor-2/03-cpp-polymorphism/listings/exo_slice_vector.cpp
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_slice_vector exo_slice_vector.cpp && ./exo_slice_vector
Harbour Songs
The Silent Code
Output 3.12. The output.
Solution

Solution of Exercise 3.6.

std::vector<Item> holds Item objects: push_back(r) copies the Item part of the recording (slicing), so the element is a plain Item and its label is Item’s. To keep objects of several classes, the vector must hold pointers that own them: std::vector<std::unique_ptr<Item>>, filled with std::make_unique<Recording>(...); the loop then calls it->label() and dispatch works. A vector of references does not exist: a reference is not an object, cannot be reseated, and cannot be an element. std::unique_ptr rather than std::shared_ptr, since the catalogue is the only owner.

Exercise 3.7 ★★

Rewrite fines_switch.c in C without any switch, with one table per kind as in Listing 3.7: a struct kind_table holding the kind’s name and a pointer to its fine function, and items that point to their kind’s table. Test that your fines equal those of the switch for every kind and every lateness from −2-2 to 400 days. What must be done to add a kind?

Solution

Solution of Exercise 3.7.

struct kind_table {                               /* what each kind must provide */
    const char *name;
    int (*fine_cents)(int days_late);
};

struct item {
    const char *title;
    const struct kind_table *kind;                /* replaces the enum tag */
};

static int standard_fine(int d) { return d * 10 < 500 ? d * 10 : 500; }
static int comic_fine(int d) { return d * 25 < 300 ? d * 25 : 300; }
static int study_fine(int d) { return d > 3 ? (d - 3) * 20 : 0; }

static const struct kind_table STANDARD = {"standard", standard_fine};
static const struct kind_table COMIC = {"comic", comic_fine};
static const struct kind_table STUDY = {"study", study_fine};

static inline int fine_cents(const struct item *it, int days_late)
{
    return days_late <= 0 ? 0 : it->kind->fine_cents(days_late);   /* no switch */
}
Fines with one table per kind, in C code/bachelor-2/03-cpp-polymorphism/exercises/fines_tables.h

tests/fines_tables_test.c compares every kind and every lateness from −2-2 to 400 with the switch. To add a kind: write its fine function and its table, two short declarations, possibly in a new file; nothing else changes. The C version has no compiler check that a table is complete, which C++’s pure virtual functions give.

Exercise 3.8 ★★

State the postconditions of Rectangle::set_width and set_height. Prove that no override of the two setters in a class Square derived from Rectangle can both keep the invariant “width equals height” and satisfy the substitution principle for the client resize_plot. Then show that an immutable Rectangle (constructor and area only) can have an immutable Square as a derived class that satisfies the principle.

Solution

Solution of Exercise 3.8.

For set_width(w): afterwards the width is w and the height is unchanged; symmetrically for set_height(h). From these, a client proves that after set_width(4); set_height(5); the area is 4×5=204 \times 5 = 20, whatever the starting sides: this is resize_plot. Suppose a Square keeps the invariant width == height. After set_height(5) the invariant forces the width to 5, so the area is 25, not 20: the client’s proven property fails, and the principle is violated. If instead the override left the width at 4, the object would no longer be square, breaking its own invariant. No override can do both, since the two requirements contradict each other on the state after set_height(5). With immutable classes, Rectangle(w, h) promises only that area() returns whwh for the sides given at construction; Square(s) constructs Rectangle(s, s), and every property provable from that specification (the area is the product of the sides, and never changes) holds for it. The problem was mutation, not squares.

Exercise 3.9 ★★

The council caps every fine at 10.00. Write a policy CappedFine that holds a reference to another policy and a cap, and returns the smaller of the two. Is it composition or inheritance, and why is it both? Compute the total owed on the town’s loans at the end of 2025 with every policy capped at 10.00, and check that a very large cap changes nothing.

Solution

Solution of Exercise 3.9.

class CappedFine : public FinePolicy {
public:
    CappedFine(const FinePolicy &inner, int cap_cents) : inner_(inner), cap_(cap_cents) {}
    int fine_cents(int d) const override
    {
        int f = inner_.fine_cents(d);
        return f < cap_ ? f : cap_;
    }
    std::string name() const override { return inner_.name() + " capped"; }

private:
    const FinePolicy &inner_;                       // has a policy; is not one of the three
    int cap_;
};
A policy that wraps a policy code/bachelor-2/03-cpp-polymorphism/exercises/capped.hpp

CappedFine derives from FinePolicy, so that the summing code can use it like any policy (inheritance of the interface); and it holds the policy it caps, to which it delegates (composition of the behaviour). It can therefore cap any policy, present or future, without a capped version of each. On the town’s loans at the end of 2025, the total owed falls from 463.45 to 309.05 with a cap of 10.00, and a cap above every fine gives 463.45 again; tests/library_test.cpp checks both figures.

Exercise 3.10 ★★★

Represent arithmetic expressions with an abstract class Expr and derived classes for numbers, variables, sums and products, owned through std::unique_ptr. Give them eval (in an environment mapping variables to values), str (fully parenthesised) and simplify, which folds operations on two numbers and applies 0+e=e0 + e = e, 1×e=e1 \times e = e and 0×e=00 \times e = 0. Put what sums and products share in a common base class. Test that ((x * (2 + 3)) + (0 * y)) simplifies to (x * 5) and evaluates as before.

Solution

Solution of Exercise 3.10.

class Binary : public Expr {                        // what Add and Mul share
public:
    Binary(ExprPtr l, ExprPtr r) : l_(std::move(l)), r_(std::move(r)) {}
    double eval(const std::map<std::string, double> &env) const override
    {
        return apply(l_->eval(env), r_->eval(env));
    }
    std::string str() const override { return "(" + l_->str() + " " + op() + " " + r_->str() + ")"; }
    ExprPtr simplify() const override
    {
        ExprPtr a = l_->simplify(), b = r_->simplify();
        if (a->constant() && b->constant())         // fold two numbers
            return std::make_unique<Num>(apply(*a->constant(), *b->constant()));
        return rebuild(std::move(a), std::move(b));
    }

protected:
    virtual double apply(double x, double y) const = 0;
    virtual const char *op() const = 0;
    virtual ExprPtr rebuild(ExprPtr a, ExprPtr b) const = 0;   // the identities of each operator
    ExprPtr l_, r_;
};
class Mul : public Binary {
public:
    using Binary::Binary;

protected:
    double apply(double x, double y) const override { return x * y; }
    const char *op() const override { return "*"; }
    ExprPtr rebuild(ExprPtr a, ExprPtr b) const override
    {
        for (const ExprPtr *e : {&a, &b})
            if ((*e)->constant() && *(*e)->constant() == 0)
                return std::make_unique<Num>(0);                // 0 * e = e * 0 = 0
        if (a->constant() && *a->constant() == 1) return b;     // 1 * e = e
        if (b->constant() && *b->constant() == 1) return a;     // e * 1 = e
        return std::make_unique<Mul>(std::move(a), std::move(b));
    }
};
The shared base of sums and products, and products code/bachelor-2/03-cpp-polymorphism/exercises/expr.hpp

Expr declares eval, str, simplify (pure) and constant, which returns the address of the value for a number and null otherwise; Num and Var are leaves. Binary writes eval, str and simplify once, in terms of three pure functions: the operation, its symbol, and rebuild, which applies the identities of each operator to the simplified operands. simplify returns a new tree and leaves the original alone. tests/exercises_test.cpp checks the example (x=1.5x = 1.5 gives 7.5 before and after), the identities, and an unbound variable.

Exercise 3.11 ★★★

A program has kk classes with virtual functions; class ii has mim_i virtual functions and NiN_i objects. Count the bytes of tables and of table pointers, with 8-byte pointers and one slot per virtual function. For the library with 3 policies of 3 virtual functions each (the destructor counts once), one object each, and 400 loans that each hold a policy pointer, compare with the C design of Listing 3.1. Then take a game with 10 kinds of particles, 4 virtual functions each, and 10610^6 particles: what fraction of the memory is table pointers if a particle holds 24 bytes of data?

Solution

Solution of Exercise 3.11.

Tables: 8∑imi8 \sum_i m_i bytes, once for the program. Table pointers: 8∑iNi8 \sum_i N_i bytes. For the library: tables 8×3×3=728 \times 3 \times 3 = 72 bytes, three policy objects with one pointer each, 24 bytes, and the 400 loans’ pointers to their policy, 3200 bytes, against 400 tags of 4 bytes, 1600 bytes, in the C design: a few kilobytes either way. For the game: tables 8×10×4=3208 \times 10 \times 4 = 320 bytes, negligible; each particle is 24+8=3224 + 8 = 32 bytes, so table pointers are a quarter of the memory (8 MB of 32 MB). Memory per object, not code size, is the price of dispatch tables when objects are small and many.

Exercise 3.12 ★★★

A virtual call chooses a function by the class of one object. Collision tests between two bodies, discs and boxes with sides parallel to the axes, depend on both. Implement bool hits(const Body &other) by double dispatch: a.hits(b) makes a virtual call on a, which makes a second virtual call on b naming its own class. Test all four pairs. How many functions does each class need with cc classes of bodies, and what must change when a class is added?

Solution

Solution of Exercise 3.12.

struct Body {
    virtual ~Body() = default;
    virtual bool hits(const Body &other) const = 0;  // first dispatch: on *this
    virtual bool hits_disc(const Disc &d) const = 0; // second dispatch: on other
    virtual bool hits_box(const Box &b) const = 0;
};

struct Disc : Body {
    double x, y, r;
    Disc(double x_, double y_, double r_) : x(x_), y(y_), r(r_) {}
    bool hits(const Body &o) const override { return o.hits_disc(*this); }
    bool hits_disc(const Disc &d) const override
    {
        return std::hypot(x - d.x, y - d.y) <= r + d.r;
    }
    bool hits_box(const Box &b) const override;
};

struct Box : Body {                                   // sides parallel to the axes
    double x0, y0, x1, y1;
    Box(double a, double b, double c, double d) : x0(a), y0(b), x1(c), y1(d) {}
    bool hits(const Body &o) const override { return o.hits_box(*this); }
    bool hits_disc(const Disc &d) const override     // the point of the box nearest the centre
    {
        double nx = std::clamp(d.x, x0, x1), ny = std::clamp(d.y, y0, y1);
        return std::hypot(d.x - nx, d.y - ny) <= d.r;
    }
    bool hits_box(const Box &b) const override
    {
        return x0 <= b.x1 && b.x0 <= x1 && y0 <= b.y1 && b.y0 <= y1;
    }
};

inline bool Disc::hits_box(const Box &b) const { return b.hits_disc(*this); }   // symmetric
Double dispatch code/bachelor-2/03-cpp-polymorphism/exercises/collide.hpp

a.hits(b) is dispatched on a’s class: Disc::hits calls b.hits_disc(*this), which is dispatched on b’s class and knows that its argument is a Disc. A disc and a box intersect when the point of the box nearest the disc’s centre (the centre clamped to the box) is within the radius. With cc classes, each needs hits and one hits_X per class: c+1c + 1 functions each, c(c+1)c(c+1) in all. Adding a class means writing its c+2c + 2 functions and adding one hits_New to every existing class: double dispatch is closed to new kinds, the reverse of what Method 3.11 achieves for single dispatch.

3.6 Problem: The town library’s lending rules

Problem 3.1

Weekend problem — The town library’s lending rules

The library of Brenmoor wants its software to handle every rule that depends on the kind of item: the fine, the loan period and the label printed on reminders. It starts from the C program of Listing 3.1 and the class design of Listing 3.10, and plans to lend maps from next year, fined 50 cents a day, at most 4.00.

Part I — The rules as a switch.

  1. In the C program, list every place that must change to add the kind MAP.
  2. The library adds two more functions on the kind: the loan period (21 days for every kind but study books, 28) and the shelf. With ff such functions and kk kinds, how many cases does the C program contain? How many must be written to add one kind, and in how many places?
  3. With -Wall, gcc warns about a switch on an enum that misses a value, but only if the switch has no default. Which switches of the program would warn after MAP is added?
  4. Using the fines of Output 3.1, give the fine of a map 2, 10 and 60 days late.
  5. Why can a C program read in from files (the kind as a string in a catalogue) not escape a switch or a table somewhere, even with classes?
  6. In which file of the class design does that unavoidable choice live?

Part II — A class hierarchy.

  1. Write the class MapFine. Which files change, and which do not?
  2. Add the loan period and the shelf to FinePolicy. Should the class keep its name? Propose one, and say which method of the chapter you follow.
  3. With ff virtual functions and kk kinds, how many function bodies does the design contain? Compare with question 2.
  4. From Output 3.9, give the number of late loans and the mean fine per late loan for each policy.
  5. Loan 27 owes 62.40 under the study policy. How many days late is it? Was it returned?
  6. The library council finds the study policy unfair to long loans and caps it at 10.00, using the CappedFine of Exercise 3.9. Which file changes?

Part III — Substitution.

  1. State the specification of fine_cents that every policy must satisfy, as a precondition on d and postconditions on the result, so that the fine-summing code is correct for every policy.
  2. The library’s reminder letter promises “the fine never exceeds 5.00”. Which policies satisfy that promise? Is it part of the specification of FinePolicy?
  3. A client test suite checks, for every policy and every dd from 0 to 400, that the fine is non-negative and non-decreasing in dd. Do the three policies pass? Does CappedFine?
  4. A clerk proposes a policy for damaged items that returns −500-500 (a refund) when d=0d = 0. Which property of question 13 does it break, and what could the summing code then compute wrongly?
  5. Is StudyFine a substitute for StandardFine, in the sense of the principle, for a client that relies on the 5.00 ceiling? For a client that relies only on question 13?
  6. Should ComicFine derive from StandardFine because both cap the fine? Argue with the principle.

Part IV — The price of dispatch.

  1. In Output 3.10, how many more nanoseconds does a virtual call on a mix of kinds cost than the switch?
  2. The library computes fines for its 400 loans once a night. Estimate the time spent in dispatch.
  3. A simulation updates 10810^8 particles of two kinds per second with one virtual call each. Estimate the share of a second spent in calls, from the same output.
  4. Name two changes to the simulation that would reduce that share, from the end of Section 3.4.
  5. Why is the measured difference between “one kind” and “mixed kinds” not explained by the two loads of Proposition 3.6?
  6. State the result of the problem: what adding a kind costs in each design, in files and places edited, and what a virtual call costs against a switch on this machine.
Solution

Solution of Problem 3.1.

1. The enum, a case in fine_cents, a case in kind_name, and every item that should become a map.

2. fkfk cases (one per function and kind). Adding a kind writes ff cases, in ff different places, plus the enum.

3. Both switches have no default, so -Wall (through -Wswitch) warns for both after MAP is added; a switch with a default would stay silent.

4. 2×50=1002 \times 50 = 100 cents, 1.00; 10×50=50010 \times 50 = 500, capped to 4.00; and 4.00 for 60 days.

5. The kind arrives as data, a string, and some code must turn each string into the right class: a table or a chain of tests is unavoidable at the boundary. Classes reduce the number of such places to one.

6. In library.hpp, in policy_for.

7. A new file holding MapFine, overriding fine_cents (std::min(50 * d, 400)) and name; policy_for gains a line for the genre of maps. FinePolicy, the other policies and the summing code do not change.

8. It now describes the rules of a kind, not only its fine: a name such as KindRules fits better. This is step 1 of Method 3.11: collect what every kind must provide.

9. Again fkfk function bodies, as many as cases, but grouped by kind, one class per kind, instead of by function: a new kind adds its ff bodies in one place.

10. Comic: 19 loans, 51.75, about 2.72 each. Standard: 58 loans, 114.10, about 1.97 each. Study: 32 loans, 297.60, 9.30 each.

11. 6240=20(d−3)6240 = 20(d - 3) gives d=315d = 315. Loan 27 was due on 19 February 2025 and is still out: 315 days to 31 December.

12. Only policy_for, which returns a capped study policy; CappedFine itself is a new file.

13. Precondition: d≥1d \geq 1, a whole number of days late (the summing code calls it only for late loans). Postcondition: the result is a whole number of cents, ≥0\geq 0, and the function does not throw. The summing code needs nothing more.

14. Standard (at most 5.00) and comic (at most 3.00); study does not (11.40 for 60 days). It is not in the specification of FinePolicy, only a property of two of its classes: the letter promises too much.

15. Yes: min⁡(10d,500)\min(10d, 500) and min⁡(25d,300)\min(25d, 300) are non-negative and non-decreasing, and max⁡(0,20(d−3))\max(0, 20(d-3)) too. CappedFine keeps both properties of the policy it wraps, since min⁡(f(d),c)\min(f(d), c) with c≥0c \geq 0 is non-negative and non-decreasing when ff is.

16. Non-negativity (and the precondition: d=0d = 0 is not a late loan). Summed with the fines, refunds would lower the total “owed” and could make it negative; and since the summing code skips d=0d = 0, the refund would never be paid anyway. A refund is a different operation and belongs in a different function.

17. For a client relying on the 5.00 ceiling: no, a study loan 60 days late breaks it. For a client relying only on question 13: yes. Substitutability is always relative to a specification.

18. No. ComicFine would inherit StandardFine’s promise of 10 cents a day and break it. What they share, “a rate per day with a ceiling”, is better expressed by one class with two parameters, or by CappedFine around a linear policy.

19. In the printed run, 7.56−3.647.56 - 3.64, about 4 nanoseconds more per call: the mixed-kinds line is about twice the switch line. (The digits change from run to run; the ratio is what to read.)

20. 400 calls of a few nanoseconds: a few microseconds a night, nothing.

21. 10810^8 calls at the mixed-kinds rate, several nanoseconds each: most of each second, before any useful work.

22. Keep the particles of each kind in their own contiguous array and loop over each array with direct calls (no pointer to follow, no unpredictable target), or keep one array of tagged values and switch; a template (Chapter 4) gives the first without writing each loop by hand.

23. Both cases do the same two loads and the same indirect call, and their objects are allocated the same way. What differs is the predictability of the target: with one kind the processor guesses the next function correctly every time, with a random mix half the time, and each wrong guess costs several nanoseconds (Chapter 11).

24. One new file per new kind, and the measured cost of a virtual call against a switch: with classes, adding a kind is one new file and one line in the function that creates the objects, against ff cases in ff places with a switch; a virtual call costs a few nanoseconds, in the printed run about twice an inlined switch when the kinds are mixed, which matters only in inner loops over millions of objects.

本章定义的术语

在术语表中查看全部 1050 个术语