Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Abstract

Inheritance allows derived classes to reuse the functionality of their base classes. Through base-class pointers or references, derived class instances can be treated as base class objects, enabling polymorphism. To ensure safe polymorphic deletion, the base class must declare a virtual destructor. Classes that manage dynamic resources should implement a destructor, copy constructor, and copy assignment operator—collectively known as the Rule of Three. For efficient resource transfer, they should also define a move constructor and move assignment operator, completing the Rule of Five.

from __init__ import *
!mkdir -p private

Motivation

Recall the implementation of the class Counter:

%%cpp
class Counter {
    int count=0;
public:
    Counter() = default;
    explicit Counter(int count) : count{count} {}
    int operator()() {
        return ++count;
    }
    void set_count(int count) { 
        if (count>=0) this->count=count; 
        else cerr << "Count cannot go negative.\n";  
    }
    operator int() const {
        return count;
    }
};

Counter counter1;
for (auto i=0; i<5; i++) cout << counter1() << ' '; cout << '\n';
counter1.set_count(10);
for (auto i=0; i<5; i++) cout << counter1() << ' '; cout << '\n';
1 2 3 4 5 
11 12 13 14 15 

We can modify the code as follows to count backwards:

%%cpp
class Counter {
    int count;
public:
    Counter() = delete;
    explicit Counter(int count) : count{count} {}
    int operator()() {
        return set_count(count-1), count;
    }
    void set_count(int count) {
        if (count>=0) this->count=count; 
        else cerr << "Count cannot go negative.\n";  
    }
    operator int() const {
        return count;
    }
};

Counter counter2(3);
for (auto i=0; i<5; i++) cout << counter2() << ' '; cout << '\n';

// error: call to deleted constructor of 'Counter'
// Counter counter3; 
// Counter counter3();
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.

Unlike the forward counter:

  1. The backward counter has the default constructor deleted using the delete keyword; and

  2. the operator() calls set_count to decrement the count.

Solution to Exercise 1

The changes are due to the following reasons:

  1. There is no meaningful single default value to start the count down.

  2. The count will eventually be decreased to 0 so set_count can ensure the count does not go negative.

Both the forward and backward counters have the same implementation for the explicit constructor, the set_count method, and the converting operator int. How to avoid code duplication?

%%cpp
class Counter {
    int count=0, step=1;
public:
    Counter() = default;
    explicit Counter(int count) : count{count} {}
    Counter(int count, int step) : count{count}, step(step) {}
    int operator()() {
        /*
        ### BEGIN SOLUTION
        */
        return set_count(count+step), count;
        /*
        ### END SOLUTION
        */
    }
    void set_count(int count) { 
        if (count>=0) this->count=count; 
        else cerr << "Count cannot go negative.\n";
    }
    operator int() const {
        return count;
    }
};

// tests
Counter counter1, counter2(3, -1);
for (auto i=0; i<5; i++) cout << counter1() << ' '; cout << '\n';
for (auto i=0; i<5; i++) cout << counter2() << ' '; cout << '\n';
/* Expected
1 2 3 4 5 
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.
*/
1 2 3 4 5 
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.

There is a slight inefficiency that operator()() needs to check if the new count is non-negative even when the step size is positive. If we want to implement more features specific for backward counter, we would have to worry about how to merge them with the forward counter. The complexity increases quickly when we want to introduce other kinds of counters later, and the code may not be backward compatible or efficient for the previous versions.

A better solution is to simply define different kinds of counters as separate derived classes of a common base class:

  • Members of the base class can be inherited, allowing code reuse.

  • Derived classes can override/overload members of its base classes, resulting in polymorphism.

Derived Class

Inheritance

The following defines the forward counter as a base class:

%%cpp
class Counter {
protected:
    int count = 0;
public:
    Counter() = default;
    explicit Counter(int count) : count{count} {}
    int operator()() {
        return ++count;
    };
    void set_count(int count) {
        if (count>=0) this->count=count; 
        else cerr << "Count cannot go negative.\n";
    }
    operator int() const {
        return count;
    }
};

Counter counter1;
for (auto i=0; i<5; i++) cout << counter1() << ' '; cout << '\n';
1 2 3 4 5 

This is the same as the previous implementation except that count now has protected member access, which make it accessible to members and friends of derived classes.

class Counter {
protected: // instead of private
    int count = 0;
public:
    ...
};

The following defines BackwardCounter as a subclass of the base class Counter:

%%cpp
class BackwardCounter : public Counter {
public:
    BackwardCounter() = delete;
    explicit BackwardCounter(int count) : Counter(count) {}
    int operator()() {
        set_count(count - 1);
        return count;
    }
};

// BackwardCounter counter2; // error: call to deleted constructor of 'BackwardCounter'
BackwardCounter counter2(3);
for (auto i=0; i<5; i++) cout << counter2() << ' '; cout << '\n';
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.

The class declaration

class BackwardCounter : public Counter { // declares Counter as a public base class
    ...
};

has a base clause that specifies the list of base classes.

  • public member specifier (public inheritance) for a base class means the access to the members of the base class is also inherited.

  • protected member specifier (protected inheritance) means that public members of the base class become protected.

  • private member specifier (private inheritance) means that both the public and protected members of the base class become private.

The constructor explicit BackwardCounter(int count) : Counter(count) {} has a member initialization list that calls the base class’s constructor Counter(count). Note that base classes are initialized before members.

%%cpp
class BackwardCounter : public Counter {
    using Counter::Counter; // not necessarily private access
public:
    BackwardCounter() = delete;
    int operator()() {
        set_count(count - 1);
        return count;
    }
};

BackwardCounter counter2(3);
for (auto i=0; i<5; i++) cout << counter2() << ' '; cout << '\n';
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.
Solution to Exercise 3

Instead of explicitly defining a constructor and call the base class constructors, using Counter::Counter creates inheriting constructors, i.e. all constructors of Counter are visible to overload resolution when initializing the derived class. If overload resolution selects one of the inherited constructors, then

  • the Base subobject from which the constructor was inherited is initialized using the inherited constructor, and

  • all other bases and members of the derived class are initialized as if by the defaulted default constructor (default member initializers are used if provided, otherwise default initialization takes place).

Polymorphism

Can we treat BackwardCounter as a Counter? That would be convenient, especially when working with multiple counters:

%%cpp
vector<Counter> counters { Counter(), BackwardCounter(3) };
for (auto &counter: counters) {
    for (auto i=0; i<5; i++) cout << counter() << ' '; cout << '\n';
}
1 2 3 4 5 
4 5 6 7 8 
Solution to Exercise 4

BackCounter(3) is converted to Counter so it counts up instead of down because the compiler dispatch statically to the operator() method implemented in Counter instead of BackCounter.

To properly override a method even if there is no compile-time information about the actual type of the class, the method should be marked using the virtual function specifier in the base class:

%%cpp
class Counter {
protected:
    int count = 0;
public:
    Counter() = default;
    explicit Counter(int count) : count{count} {}
    virtual ~Counter() = default; // allow polymorphic deletion

    virtual int operator()() {  // can be overridden
        return ++count;
    }
    void set_count(int count) {
        if (count>=0) this->count=count; 
        else cerr << "Count cannot go negative.\n";
    }
    operator int() const {
        return count;
    }
};
%%hermes
Explain in a paragraph why virtual constructor is not allowed in C++.
Loading...
🌿 Fork/new: main (will create on click)

We should also update the code for BackwardCounter:

class BackwardCounter : public Counter {
public:
    ...
    virtual int operator()() override {
        ...
    }
};
%%cpp
class BackwardCounter : public Counter {
public:
    BackwardCounter() = delete;
    explicit BackwardCounter(int count) : Counter(count) {}
    virtual int operator()() override {
        set_count(count - 1);
        return count;
    }
};

There is no need to declare operator() in the derived case as virtual if it should not be further overriden.

It seems to work now:

%%cpp
BackwardCounter counter1(3);
Counter *counter2=&counter1;
for (auto i=0; i<5; i++) cout << (*counter2)() << ' '; cout << '\n';
Counter &counter3=counter1;
for (auto i=0; i<5; i++) cout << counter3() << ' '; cout << '\n';
2 1 0 0 0 
0 0 0 0 0 
Count cannot go negative.
Count cannot go negative.
Count cannot go negative.
Count cannot go negative.
Count cannot go negative.
Count cannot go negative.
Count cannot go negative.

Even though *counter2 and counter3 have type Counter instead of BackwardCounter, they both use int operator()() defined in BackwardCounter. This is achieved using dynamic dispatch for virtual functions.

%%hermes
Explain in a paragraph or two how C++ implements dynamic dispatch for 
virtual functions. Why the name virtual?
Loading...
↻ Session: main (ACP: 15890faf-575…)

Note also that there is no need to perform type casting when converting the address of a derived class to that of the base class. In comparison, reinterpret_cast is required for the reverse conversion:

%%cpp
Counter counter1;
BackwardCounter *counter2=reinterpret_cast<BackwardCounter *>(&counter1);
for (auto i=0; i<5; i++) cout << (*counter2)() << ' '; cout << '\n';
BackwardCounter &counter3=reinterpret_cast<BackwardCounter &>(counter1);
for (auto i=0; i<5; i++) cout << counter3() << ' '; cout << '\n';
1 2 3 4 5 
6 7 8 9 10 

Such conversion is unusual, however, since Counter does not initialize any new members introduced in BackwardCounter.

Solution to Exercise 5

They do not count backward since the vptr of each object still points to the vtable of their actual (dynamic) type Counter.

Base Class Pointers

Unfortunately, the issue remains even after using virtual function specifier:

%%cpp
vector<Counter> counters { Counter(), BackwardCounter(3) };
for (auto &counter: counters) {
    for (auto i=0; i<5; i++) cout << counter() << ' '; cout << '\n';
}
1 2 3 4 5 
4 5 6 7 8 
%%cpp
BackwardCounter counter1(3);
Counter counter2=counter1;            // copied
for (auto i=0; i<5; i++) cout << counter2() << ' '; cout << '\n';
Counter counter3=std::move(counter1); // moved
for (auto i=0; i<5; i++) cout << counter3() << ' '; cout << '\n';
cout << static_cast<Counter>(counter1)() << '\n';
4 5 6 7 8 
4 5 6 7 8 
4

To fix the issue, we should use std::vector<Counter *> instead of std::vector<Counter>:

%%cpp
Counter counter1;
BackwardCounter counter2(3);
vector<Counter *> counters { &counter1, &counter2 };
for (auto counter: counters) {
    for (auto i=0; i<5; i++) cout << (*counter)() << ' '; cout << '\n';
}
1 2 3 4 5 
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.
%%cpp
{
    /*
    ### BEGIN SOLUTION
    */
    vector<Counter *> counters { new Counter(), new BackwardCounter(3) };
    /*
    ### END SOLUTION
    */
    for (auto &counter: counters) {
        for (auto i=0; i<5; i++) cout << (*counter)() << ' '; cout << '\n';
        delete counter;  // avoid memory leak
        counter=nullptr; // avoid double deletion
    }
    /* Expected
    1 2 3 4 5 
    2 1 0 0 0 
    Count cannot go negative.
    Count cannot go negative.
    */
} // counters out of scope
1 2 3 4 5 
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.

To avoid manually releasing the memory, we can use smart pointers such as std::unique_ptr from <memory>:

%%cpp
Counter *count1;
{
    // vector<unique_ptr<Counter>> counters { make_unique<Counter>(), make_unique<BackwardCounter>(3) }; // fails as unique_ptr is non-copyable
    vector<unique_ptr<Counter>> counters;
    counters.push_back(make_unique<Counter>());
    counters.push_back(make_unique<BackwardCounter>(3));
    
    for (auto& counter : counters) {
        for (int i = 0; i < 5; ++i) cout << (*counter)() << ' '; cout << '\n';
    }
} // members of counters destroyed automatically
1 2 3 4 5 
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.

To create copyable smart pointers, we can instead use the smart pointer std::shared_ptr in <memory>:

%%cpp
vector<shared_ptr<Counter>> counters { make_shared<Counter>(), make_shared<BackwardCounter>(3) };

for (auto& counter : counters) {
    for (int i = 0; i < 5; ++i) cout << (*counter)() << ' '; cout << '\n';
}
1 2 3 4 5 
2 1 0 0 0 
Count cannot go negative.
Count cannot go negative.

Memory Management

UndoRedoCounter

Consider implementing a counter that can undo and redo changes to its count. We need to modify Counter slightly to allow set_count to be overriden as well:

%%cpp
class Counter {
protected:
    int count = 0;
public:
    Counter() = default;
    explicit Counter(int count) : count{count} {}
    virtual ~Counter() = default;

    virtual int operator()() {
        return ++count;
    }
    virtual bool set_count(int count) {
        if (count>=0) return this->count=count, true; 
        else return cerr << "Count cannot go negative.\n", false;
    }
    operator int() const {
        return count;
    }
};

The following is an implementation that uses a circular buffer to keep a history of count values:

%%cpp
class UndoRedoCounter : public Counter {
    int *buffer;
    size_t historysize, head, tail, current;

    size_t after(size_t pos) const { return (pos+1) % historysize; }
    size_t before(size_t pos) const { return (historysize+pos-1) % historysize; }

    int push(int value) {
        if (head == before(tail)) tail=after(tail);
        return buffer[head = current = after(current)] = value;
    }

public:
    UndoRedoCounter() : UndoRedoCounter(0) {}
    explicit UndoRedoCounter(int count, int historysize=5)
    : Counter(count), historysize(historysize), head(0), tail(0), current(-1) {
        if (historysize<1) throw runtime_error("History size must be at least 1.");
        buffer = new int[historysize];
        push(count);
    }
    ~UndoRedoCounter() override {
        delete[] buffer;
    }

    int operator()() override {
        return push(Counter::operator()());
    }
    bool set_count(int count) override {
        return Counter::set_count(count) && (push(count), true);
    }

    bool can_undo() const { return current != tail; }
    bool can_redo() const { return current != head; }
    int undo() {
        if (can_undo()) current = before(current); else cerr << "Cannot undo.\n";
        return count=buffer[current];
    }
    int redo() {
        if (can_redo()) current = after(current); else cerr << "Cannot redo.\n";
        return count=buffer[current];
    }
    void print_history() const {
        cout << "History Buffer [size=" << historysize << "]:\n";
        for (size_t i = 0; i < historysize; ++i) {
            cout << "[" << i << "] " << buffer[i];
            if (i == head) cout << " <- head";
            if (i == tail) cout << " <- tail";
            if (i == current) cout << " <- current";
            cout << "\n";
        }
    }
};

UndoRedoCounter c;
c.print_history();
History Buffer [size=5]:
[0] 0 <- head <- tail <- current
[1] 22850
[2] 0
[3] 0
[4] 32

The derived class UndoRedoCounter used new private members to keep track of the history as follows:

class UndoRedoCounter : public Counter {
    int *buffer;
    size_t historysize, head, tail, current;

    size_t after(size_t pos) const { return (pos+1) % historysize; }
    size_t before(size_t pos) const { return (historysize+pos-1) % historysize; }

    int push(int value) {
        if (head == before(tail)) tail=after(tail);
        return buffer[head = current = after(current)] = value;
    }
    ...
public:
    ...
    void print_history() const {
        cout << "History Buffer [size=" << historysize << "]:\n";
        for (size_t i = 0; i < historysize; ++i) {
            cout << "[" << i << "] " << buffer[i];
            if (i == head) cout << " <- head";
            if (i == tail) cout << " <- tail";
            if (i == current) cout << " <- current";
            cout << "\n";
        }
    }
};
  • int *buffer is a dynamically allocated array that stores the history of counter values.

  • size_t historysize is the size of the buffer.

  • size_t head is the index of the most recent entry in the buffer.

  • size_t tail is the index of the oldest entry still retained in the buffer.

  • size_t current is the index of the current value.

  • The method void print_history() prints the contents of the history buffer annotated with the position of head, tail, and current.

Solution to Exercise 7

The function pushes value into the history buffer and return it:

  • If head is right before tail before the push, the buffer is full so the value will overwrite the oldest value. Therefore, tail is updated to the index of the second oldest value.

  • The head and current is updated to the index after current, where the value is written to.

Polymorphic Destruction

class UndoRedoCounter : public Counter {
    ...

public:
    UndoRedoCounter() : UndoRedoCounter(0) {} // delegating constructor for code reuse
    explicit UndoRedoCounter(int count, int historysize=5)
    : Counter(count), historysize(historysize), head(0), tail(0), current(-1) {
        if (historysize<1) throw runtime_error("History size must be at least 1.");
        buffer = new int[historysize];
        push(count);
    }
    ~UndoRedoCounter() override {
        delete[] buffer;
    } // `Counter::~Counter()` called automatically after `~UndoRedoCounter()`
    ...
};
  • The default constructor UndoRedoCounter() : UndoRedoCounter(0) is a delegating constructor that reuse the code of the explicit constructor below, with the count default to 0.

  • The explicit constructor explicit UndoRedoCounter(int count, int historysize=5) initializes private members as follows:

    • The count is initialized by reusing the base class constructor explicit Counter(int count).

    • Since the current count must be stored in the history as well, the constructor ensures historysize is at least 1 before allocating the memory for buffer.

    • current is initialized to -1 since it will be incremented to 0 by push(count);.

    • head and tail is initialized to 0, which will be the position of the current count after the push.

  • The destructor ~UndoRedoCounter() override releases the memory allocated to buffer. The destructor of the base class is also called in reverse order of construction.

%%cpp
UndoRedoCounter c;
c.print_history();
History Buffer [size=5]:
[0] 0 <- head <- tail <- current
[1] 22850
[2] 0
[3] 0
[4] 5
Solution to Exercise 8

If head is set to -1 instead, push(count) will mistaken the buffer to be full (head == before(tail)) and set tail=after(tail). That means the uninitialized values of buffer are wrongly regarded as the previous values of count.

Solution to Exercise 9

If ~Counter() is not declared virtual, the destructor of the derived class (UndoRedoCounter) will never be invoked when an object is destroyed through a base class pointer Counter*. As a consequence, any resources that UndoRedoCounter allocated, such as its internal buffer, remain unreclaimed, leading to a memory leak.

{
    Counter *c=UndoRedoCounter();
} // c goes out of scope but `~UndoRedoCounter` is not executed.

By declaring the base‑class destructor as virtual, the runtime dispatch mechanism ensures that the destructor (~UndoRedoCounter()) runs even when the object is accessed via a base‑class pointer. This guarantees that any resources held by UndoRedoCounter are properly released.

Accessing Members

class UndoRedoCounter : public Counter {
...

public:
    ...
    int operator()() override {
        return push(Counter::operator()());
    }
    bool set_count(int count) override {
        return Counter::set_count(count) && (push(count), true);
    }
    ...
};

Both int operator()() and bool set_count(int count) reuse the corresponding methods they override, which can be accessed using the scope resolution operator :: in addition to the using declaration for inheriting constructors. The updated count is then pushed to the history buffer.

%%cpp
UndoRedoCounter c;
cout << c << ' ' << c() << ' ';         // count = 1
cout << c() << ' ';                     // count = 2
if (c.set_count(10)) cout << c << '\n'; // count = 10
c.print_history();
0 1 2 10
History Buffer [size=5]:
[0] 0 <- tail
[1] 1
[2] 2
[3] 10 <- head <- current
[4] 32
class UndoRedoCounter : public Counter {
...

public:
    ...
    bool can_undo() const { return current != tail; }
    ...
    int undo() {
        if (can_undo()) current = before(current); else cerr << "Cannot undo.\n";
        return count=buffer[current];
    }
    ...
};
  • int undo() moves current back by one position if doing so does not exceed the tail, i.e., the condition current != tail returned by can_undo, and

  • count is then updated to the value of the buffer at the current position.

%%cpp
UndoRedoCounter c;
cout << c << ' ' << c() << ' ';         // count = 1
cout << c() << ' ';                     // count = 2
if (c.set_count(10)) cout << c << '\n'; // count = 10
cout << c.undo() << '\n';        // count = 2
c.print_history();
cout << c.undo() << ' ';        // count = 1
cout << c.undo() << '\n';        // count = 0
c.print_history();
cout << c.undo() << '\n';       // cannot undo beyond the first change
0 1 2 10
2
History Buffer [size=5]:
[0] 0 <- tail
[1] 1
[2] 2 <- current
[3] 10 <- head
[4] 32
1 0
History Buffer [size=5]:
[0] 0 <- tail <- current
[1] 1
[2] 2
[3] 10 <- head
[4] 32
0
Cannot undo.
%%cpp
UndoRedoCounter c;
for (int i=0; i<6; i++) cout << c() << ' '; cout << '\n';      // count = 6
c.print_history();
for (int i=0; i<4; i++) cout << c.undo() << ' '; cout << '\n'; // count = 2
c.print_history();
cout << c.undo() << '\n';       // can undo at most `historysize-1` times
1 2 3 4 5 6 
History Buffer [size=5]:
[0] 5
[1] 6 <- head <- current
[2] 2 <- tail
[3] 3
[4] 4
5 4 3 2 
History Buffer [size=5]:
[0] 5
[1] 6 <- head
[2] 2 <- tail <- current
[3] 3
[4] 4
2
Cannot undo.
class UndoRedoCounter : public Counter {
...

public:
    ...
    bool can_redo() const { return current != head; }
    ...
    int redo() {
        if (can_redo()) current = after(current); else cerr << "Cannot redo.\n";
        return count=buffer[current];
    }
    ...
};
  • int redo() moves current forward by one position if doing so does not exceed the head, i.e., the condition current != head returned by can_redo, and

  • count is then updated to the value of the buffer at the current position.

%%cpp
UndoRedoCounter c;
cout << c << ' ' << c() << ' ';             // count = 1
if (c.set_count(10)) cout << c << '\n'; // count = 10
cout << c.undo() << ' ';        // count = 1
cout << c.undo() << ' ';        // count = 0
cout << c.redo() << '\n';        // count = 1
c.print_history();
cout << c.redo() << '\n';        // count = 10
c.print_history();
cout << c.redo() << '\n';       // cannot redo after the last change
0 1 10
1 0 1
History Buffer [size=5]:
[0] 0 <- tail
[1] 1 <- current
[2] 10 <- head
[3] 0
[4] 32
10
History Buffer [size=5]:
[0] 0 <- tail
[1] 1
[2] 10 <- head <- current
[3] 0
[4] 32
10
Cannot redo.

Note that we cannot access new methods defined in the derived class through a base class pointer:

%%cpp
unique_ptr<Counter> c { make_unique<UndoRedoCounter>() };
cout << *c << ' ' << (*c)() << ' ';   // count = 1
// cout << (*c).undo() << ' ';        // error: no member named 'undo' in 'Counter'
0 1 
Solution to Exercise 10

This is because undo is not defined in Counter so the compiler cannot resolve it statically, unlike other virtual methods defined in the base class.

To fix the issue, we can use dynamic_cast:

%%cpp
unique_ptr<Counter> c { make_unique<UndoRedoCounter>() };
cout << *c << ' ' << (*c)() << ' ';   // count = 1

UndoRedoCounter *raw=dynamic_cast<UndoRedoCounter*>(c.get());
if (raw) {
    unique_ptr<UndoRedoCounter> d(raw);
    c.release();
    cout << d->undo() << ' ';
}
0 1 0 
%%hermes
Explain in a paragraph or two how dynamic_cast can be used to convert a derived
class accessed through its base class pointer back to the derived class?
Loading...
🌿 Fork/new: main (will create on click)

Rule of Three

UndoRedoCounter appears to fail:

%%cpp
UndoRedoCounter c1, c2=c1;               // c1: 0    c2: 0
if (c2.set_count(10)) cout << c2 << ' '; //              10         
cout << c1() << ' ';                     //     1
cout << c2() << ' ';                     //              11
cout << c1.undo() << ' ';                //     0      
cout << c2.undo() << '\n';               //              10?
10 1 11 0 1

Shouldn’t c2.undo() return the count 10 set by c2.set_count(10)?

It works if we directly initialize the count of c2 to 10:

%%cpp
UndoRedoCounter c1, c2(10);              // c1: 0    c2: 10        
cout << c1() << ' ';                     //     1
cout << c2() << ' ';                     //              11
cout << c1.undo() << ' ';                //     0
cout << c2.undo() << '\n';               //              10
1 11 0 10

But the above is not a fix. There is an even bigger memory issue:

Let us figure out what is wrong before quickly jumping to a fix:

%%cpp
UndoRedoCounter c1, c2=c1;                // c1: 0    c2: 0
if (c2.set_count(10)) cout << c2 << '\n'; //              10
c2.print_history();
cout << c1() << '\n';                     //     1
c2.print_history();
10
History Buffer [size=5]:
[0] 0 <- tail
[1] 10 <- head <- current
[2] 0
[3] 0
[4] 32
1
History Buffer [size=5]:
[0] 0 <- tail
[1] 1 <- head <- current
[2] 0
[3] 0
[4] 32
Solution to Exercise 11

Note that c1 and c2 are destroyed when they go out of the block scope of the compound expression. When c2 is destroyed, it executes delete[] buffer, leaving c1 with a dangling pointer buffer. When c1 is destroyed, delete[] buffer is deleted again. Double deletion leads to undefined behavior and memory corruption that cause the crash.

To fix the issue, we should either:

  1. Delete the copy constructor if copying is not intended:

    UndoRedoCounter(const UndoRedoCounter&) = delete;
  2. Or, define the copy constructor to perform a deep copy of the buffer.

    UndoRedoCounter(const UndoRedoCounter& other)
        : Counter(other), historysize(other.historysize),
          head(other.head), tail(other.tail), current(other.current) {
        buffer = new int[historysize];
        for (size_t i = 0; i < historysize; ++i)
            buffer[i] = other.buffer[i];
    }

    This constructor:

    • Copies the base Counter part using its copy constructor.

    • Allocates a new buffer of the same size.

    • Copies each element from the source buffer.

We will go with the second fix:

%%cpp
class UndoRedoCounter : public Counter {
    int *buffer;
    size_t historysize, head, tail, current;

    size_t after(size_t pos) const { return (pos+1) % historysize; }
    size_t before(size_t pos) const { return (historysize+pos-1) % historysize; }

    int push(int value) {
        if (head == before(tail)) tail=after(tail);
        return buffer[head = current = after(current)] = value;
    }

public:
    UndoRedoCounter() : UndoRedoCounter(0) {}
    explicit UndoRedoCounter(int count, int historysize=5)
    : Counter(count), historysize(historysize), head(0), tail(0), current(-1) {
        if (historysize<1) throw runtime_error("History size must be at least 1.");
        buffer = new int[historysize];
        push(count);
    }
    UndoRedoCounter(const UndoRedoCounter& other)
        : Counter(other), historysize(other.historysize),
          head(other.head), tail(other.tail), current(other.current) {
        buffer = new int[historysize];
        for (size_t i = 0; i < historysize; ++i)
            buffer[i] = other.buffer[i];
    }
    ~UndoRedoCounter() override {
        delete[] buffer;
    }

    int operator()() override {
        return push(Counter::operator()());
    }
    bool set_count(int count) override {
        return Counter::set_count(count) && (push(count), true);
    }

    bool can_undo() const { return current != tail; }
    bool can_redo() const { return current != head; }
    int undo() {
        if (can_undo()) current = before(current); else cerr << "Cannot undo.\n";
        return count=buffer[current];
    }
    int redo() {
        if (can_redo()) current = after(current); else cerr << "Cannot redo.\n";
        return count=buffer[current];
    }
    void print_history() const {
        cout << "History Buffer [size=" << historysize << "]:\n";
        for (size_t i = 0; i < historysize; ++i) {
            cout << "[" << i << "] " << buffer[i];
            if (i == head) cout << " <- head";
            if (i == tail) cout << " <- tail";
            if (i == current) cout << " <- current";
            cout << "\n";
        }
    }
};

It appears to work:

%%cpp
{
    UndoRedoCounter c1, c2=c1;               // c1: 0    c2: 0
    if (c2.set_count(10)) cout << c2 << ' '; //              10         
    cout << c1() << ' ';                     //     1
    cout << c2() << ' ';                     //              11
    cout << c1.undo() << ' ';                //     0      
    cout << c2.undo() << '\n';               //              10?
}
10 1 11 0 10

Not really...

%%cpp
UndoRedoCounter c1, c2;                  // c1: 0    c2: 0
c2=c1;
if (c2.set_count(10)) cout << c2 << ' '; //              10         
cout << c1() << ' ';                     //     1
cout << c2() << ' ';                     //              11
cout << c1.undo() << ' ';                //     0      
cout << c2.undo() << '\n';               //              10?
10 1 11 0 1
Solution to Exercise 12

The copy assignment c2 = c1 does not invoke delete[] buffer, so the heap memory that c1 originally allocated is never freed. After the assignment, c1.buffer simply points to whatever c2.buffer points to, leaving the original allocation inaccessible and causing a memory leak.

To fix the issue, we should either:

  1. Delete the copy assignment operator if copying is not intended:

    UndoRedoCounter& operator=(const UndoRedoCounter&) = delete;
  2. Or, define the copy assignment operator to perform a deep copy of the buffer.

    UndoRedoCounter& operator=(const UndoRedoCounter& other) {
       if (this == &other) return *this; // self-assignment check
        Counter::operator=(other);       // assign base class instance
        delete[] buffer;                 // free existing buffer
        historysize = other.historysize;
        head = other.head;
        tail = other.tail;
        current = other.current;
        buffer = new int[historysize];
        for (size_t i = 0; i < historysize; ++i)
            buffer[i] = other.buffer[i];
        return *this;
    }

    This operator:

    • Checks for self-assignment.

    • Assigns the base class part.

    • Deletes the old buffer and allocates a new one.

    • Copies the buffer contents.

%%cpp
class UndoRedoCounter : public Counter {
    int *buffer;
    size_t historysize, head, tail, current;

    size_t after(size_t pos) const { return (pos+1) % historysize; }
    size_t before(size_t pos) const { return (historysize+pos-1) % historysize; }

    int push(int value) {
        if (head == before(tail)) tail=after(tail);
        return buffer[head = current = after(current)] = value;
    }

public:
    UndoRedoCounter() : UndoRedoCounter(0) {}
    explicit UndoRedoCounter(int count, int historysize=5)
    : Counter(count), historysize(historysize), head(0), tail(0), current(-1) {
        if (historysize<1) throw runtime_error("History size must be at least 1.");
        buffer = new int[historysize];
        push(count);
    }
    UndoRedoCounter(const UndoRedoCounter& other)
        : Counter(other), historysize(other.historysize),
          head(other.head), tail(other.tail), current(other.current) {
        buffer = new int[historysize];
        for (size_t i = 0; i < historysize; ++i)
            buffer[i] = other.buffer[i];
    }
    ~UndoRedoCounter() override {
        delete[] buffer;
    }

    UndoRedoCounter& operator=(const UndoRedoCounter& other) {
       if (this == &other) return *this; // self-assignment check
        Counter::operator=(other); // assign base class part
        delete[] buffer; // free existing buffer
        historysize = other.historysize;
        head = other.head;
        tail = other.tail;
        current = other.current;
        buffer = new int[historysize];
        for (size_t i = 0; i < historysize; ++i)
            buffer[i] = other.buffer[i];
        return *this;
    }
    int operator()() override {
        return push(Counter::operator()());
    }
    bool set_count(int count) override {
        return Counter::set_count(count) && (push(count), true);
    }

    bool can_undo() const { return current != tail; }
    bool can_redo() const { return current != head; }
    int undo() {
        if (can_undo()) current = before(current); else cerr << "Cannot undo.\n";
        return count=buffer[current];
    }
    int redo() {
        if (can_redo()) current = after(current); else cerr << "Cannot redo.\n";
        return count=buffer[current];
    }
    void print_history() const {
        cout << "History Buffer [size=" << historysize << "]:\n";
        for (size_t i = 0; i < historysize; ++i) {
            cout << "[" << i << "] " << buffer[i];
            if (i == head) cout << " <- head";
            if (i == tail) cout << " <- tail";
            if (i == current) cout << " <- current";
            cout << "\n";
        }
    }
};

It appears to work now:

%%cpp
UndoRedoCounter c1, c2;                  // c1: 0    c2: 0
c2=c1;
if (c2.set_count(10)) cout << c2 << ' '; //              10         
cout << c1() << ' ';                     //     1
cout << c2() << ' ';                     //              11
cout << c1.undo() << ' ';                //     0      
cout << c2.undo() << '\n';               //              10?
10 1 11 0 10
%%cpp
class UndoRedoCounter : public Counter {
    int *buffer;
    size_t historysize, head, tail, current;

    size_t after(size_t pos) const { return (pos+1) % historysize; }
    size_t before(size_t pos) const { return (historysize+pos-1) % historysize; }

    int push(int value) {
        if (head == before(tail)) tail=after(tail);
        return buffer[head = current = after(current)] = value;
    }
    void copy_from(const UndoRedoCounter& other) {
        /*
        ### BEGIN SOLUTION
        */
        historysize = other.historysize;
        head = other.head;
        tail = other.tail;
        current = other.current;
        buffer = new int[historysize];
        for (size_t i = 0; i < historysize; ++i)
            buffer[i] = other.buffer[i];
        /*
        ### END SOLUTION
        */
    }

public:
    UndoRedoCounter() : UndoRedoCounter(0) {}
    explicit UndoRedoCounter(int count, int historysize=5)
    : Counter(count), historysize(historysize), head(0), tail(0), current(-1) {
        if (historysize<1) throw runtime_error("History size must be at least 1.");
        buffer = new int[historysize];
        push(count);
    }
    UndoRedoCounter(const UndoRedoCounter& other)
        : Counter(other) {
        copy_from(other);
    }
    ~UndoRedoCounter() override {
        delete[] buffer;
    }

    UndoRedoCounter& operator=(const UndoRedoCounter& other) {
        if (this == &other) return *this;
        Counter::operator=(other);
        delete[] buffer;
        copy_from(other);
        return *this;
    }
    int operator()() override {
        return push(Counter::operator()());
    }
    bool set_count(int count) override {
        return Counter::set_count(count) && (push(count), true);
    }

    bool can_undo() const { return current != tail; }
    bool can_redo() const { return current != head; }
    int undo() {
        if (can_undo()) current = before(current); else cerr << "Cannot undo.\n";
        return count=buffer[current];
    }
    int redo() {
        if (can_redo()) current = after(current); else cerr << "Cannot redo.\n";
        return count=buffer[current];
    }
    void print_history() const {
        cout << "History Buffer [size=" << historysize << "]:\n";
        for (size_t i = 0; i < historysize; ++i) {
            cout << "[" << i << "] " << buffer[i];
            if (i == head) cout << " <- head";
            if (i == tail) cout << " <- tail";
            if (i == current) cout << " <- current";
            cout << "\n";
        }
    }
};
%%cpp
// tests
{
    UndoRedoCounter c1, c2=c1;               // c1: 0    c2: 0
    if (c2.set_count(10)) cout << c2 << ' '; //              10         
    cout << c1() << ' ';                     //     1
    cout << c2() << ' ';                     //              11
    cout << c1.undo() << ' ';                //     0      
    cout << c2.undo() << '\n';                //              10?
}
{
    UndoRedoCounter c1, c2;                  // c1: 0    c2: 0
    c2=c1;
    if (c2.set_count(10)) cout << c2 << ' '; //              10         
    cout << c1() << ' ';                     //     1
    cout << c2() << ' ';                     //              11
    cout << c1.undo() << ' ';                //     0      
    cout << c2.undo() << '\n';                //              10?
}
10 1 11 0 10
10 1 11 0 10

The issue is summarized into the following rule of thumb for C++ programming:

Rule of Five

Note that there is no memory corruption for the move semantics:

%%cpp
// tests
{
    UndoRedoCounter c1, c2=std::move(c1);    // c1: 0    c2: 0
    if (c2.set_count(10)) cout << c2 << ' '; //              10         
    cout << c1() << ' ';                     //     1
    cout << c2() << ' ';                     //              11
    cout << c1.undo() << ' ';                //     0      
    cout << c2.undo() << '\n';               //              10?
}
{
    UndoRedoCounter c1, c2;                  // c1: 0    c2: 0
    c2=std::move(c1);
    if (c2.set_count(10)) cout << c2 << ' '; //              10         
    cout << c1() << ' ';                     //     1
    cout << c2() << ' ';                     //              11
    cout << c1.undo() << ' ';                //     0      
    cout << c2.undo() << '\n';               //              10?
}
10 1 11 0 10
10 1 11 0 10
Solution to Exercise 14

Since UndoRedoCounter implements its own copy constructor or copy‑assignment operator, the compiler will not generate the implicitly declared move constructor and move‑assignment operator. Consequently, the expressions UndoRedoCounter c2=std::move(c1); and c2=std::move(c1); will bind to the copy constructor and copy assignment operator instead of a move version because

  • the move operations are absent and

  • the temporary returned by std::move is treated as an rvalue that can be pass by constant lvalue reference to the copy constructor and copy assignment operator.

The move constructor can be defined as follows to transfer the memory allocated to the buffer:

UndoRedoCounter(UndoRedoCounter&& other) noexcept
    : Counter(std::move(other)),
      buffer(other.buffer),      // transfer allocated memory
      historysize(other.historysize),
      head(other.head),
      tail(other.tail),
      current(other.current) {
    other.buffer = nullptr;      // double deletion is okay for nullptr
    other.historysize = 0;       // prevent access to buffer
}

Move Assignment Operator

UndoRedoCounter& operator=(UndoRedoCounter&& other) noexcept {
    if (this == &other) return *this;     // self-move check
    Counter::operator=(std::move(other)); // move base class instance
    delete[] buffer;                      // free existing buffer
    buffer = other.buffer;
    historysize = other.historysize;
    head = other.head;
    tail = other.tail;
    current = other.current;
    other.buffer = nullptr;
    other.historysize = 0;
    return *this;
}
%%cpp
class UndoRedoCounter : public Counter {
    int *buffer;
    size_t historysize, head, tail, current;

    size_t after(size_t pos) const { return (pos+1) % historysize; }
    size_t before(size_t pos) const { return (historysize+pos-1) % historysize; }

    int push(int value) {
        if (head == before(tail)) tail=after(tail);
        return buffer[head = current = after(current)] = value;
    }

public:
    UndoRedoCounter() : UndoRedoCounter(0) {}
    explicit UndoRedoCounter(int count, int historysize=5)
    : Counter(count), historysize(historysize), head(0), tail(0), current(-1) {
        if (historysize<1) throw runtime_error("History size must be at least 1.");
        buffer = new int[historysize];
        push(count);
    }
    UndoRedoCounter(const UndoRedoCounter& other)
        : Counter(other), historysize(other.historysize),
          head(other.head), tail(other.tail), current(other.current) {
        buffer = new int[historysize];
        for (size_t i = 0; i < historysize; ++i)
            buffer[i] = other.buffer[i];
    }
    UndoRedoCounter(UndoRedoCounter&& other) noexcept
        : Counter(std::move(other)),
          buffer(other.buffer),
          historysize(other.historysize),
          head(other.head),
          tail(other.tail),
          current(other.current) {
        other.buffer = nullptr;
        other.historysize = 0;
    }
    ~UndoRedoCounter() override {
        delete[] buffer;
    }

    UndoRedoCounter& operator=(const UndoRedoCounter& other) {
       if (this == &other) return *this; // self-assignment check
        Counter::operator=(other); // assign base class part
        delete[] buffer; // free existing buffer
        historysize = other.historysize;
        head = other.head;
        tail = other.tail;
        current = other.current;
        buffer = new int[historysize];
        for (size_t i = 0; i < historysize; ++i)
            buffer[i] = other.buffer[i];
        return *this;
    }
    UndoRedoCounter& operator=(UndoRedoCounter&& other) noexcept {
        if (this == &other) return *this;
        Counter::operator=(std::move(other));
        delete[] buffer;
        buffer = other.buffer;
        historysize = other.historysize;
        head = other.head;
        tail = other.tail;
        current = other.current;
        other.buffer = nullptr;
        other.historysize = 0;
        return *this;
    }
    int operator()() override {
        return push(Counter::operator()());
    }
    bool set_count(int count) override {
        return Counter::set_count(count) && (push(count), true);
    }

    bool can_undo() const { return current != tail; }
    bool can_redo() const { return current != head; }
    int undo() {
        if (can_undo()) current = before(current); else cerr << "Cannot undo.\n";
        return count=buffer[current];
    }
    int redo() {
        if (can_redo()) current = after(current); else cerr << "Cannot redo.\n";
        return count=buffer[current];
    }
    void print_history() const {
        cout << "History Buffer [size=" << historysize << "]:\n";
        for (size_t i = 0; i < historysize; ++i) {
            cout << "[" << i << "] " << buffer[i];
            if (i == head) cout << " <- head";
            if (i == tail) cout << " <- tail";
            if (i == current) cout << " <- current";
            cout << "\n";
        }
    }
};

With these additions, the class now fully supports

  • polymorphic deletion with virtual destructor;

  • deep copying by the copy constructor/assignment; and

  • efficient transfer of resource by the move constructor/assignment.

%%cpp
{
    UndoRedoCounter c1(10);   
    UndoRedoCounter c2=std::move(c1);
    cout << "c1:\n";
    c1.print_history();
    cout << "c2:\n";
    c2.print_history();
}
{
    UndoRedoCounter c1(10), c2;
    c2=std::move(c1);
    cout << "c1:\n";
    c1.print_history();
    cout << "c2:\n";
    c2.print_history();
}
c1:
History Buffer [size=0]:
c2:
History Buffer [size=5]:
[0] 10 <- head <- tail <- current
[1] 22850
[2] 0
[3] 0
[4] 0
c1:
History Buffer [size=0]:
c2:
History Buffer [size=5]:
[0] 10 <- head <- tail <- current
[1] 22850
[2] 0
[3] 0
[4] 0
%%cpp
class UndoRedoCounter : public Counter {
    vector<int> buffer;
    size_t head, tail, current;

    size_t after(size_t pos) const { return (pos + 1) % buffer.size(); }
    size_t before(size_t pos) const { return (buffer.size() + pos - 1) % buffer.size(); }

    int push(int value) {
        if (head == before(tail)) tail = after(tail);
        current = after(current);
        head = current;
        buffer[current] = value;
        return value;
    }

public:
    /*
    ### BEGIN SOLUTION
    */
    UndoRedoCounter() : UndoRedoCounter(0) {}
    explicit UndoRedoCounter(int count, size_t historysize = 5)
        : Counter(count), head(0), tail(0), current(-1), buffer(historysize) {
        if (historysize < 1) throw std::runtime_error("History size must be at least 1.");
        push(count);
    }

    int operator()() override {
        return push(Counter::operator()());
    }

    bool set_count(int count) override {
        return Counter::set_count(count) && (push(count), true);
    }

    bool can_undo() const { return current != tail; }
    bool can_redo() const { return current != head; }

    int undo() {
        if (can_undo()) current = before(current); else std::cerr << "Cannot undo.\n";
        return count = buffer[current];
    }

    int redo() {
        if (can_redo()) current = after(current); else std::cerr << "Cannot redo.\n";
        return count = buffer[current];
    }

    void print_history() const {
        std::cout << "History Buffer [size=" << buffer.size() << "]:\n";
        for (size_t i = 0; i < buffer.size(); ++i) {
            std::cout << "[" << i << "] " << buffer[i];
            if (i == head) std::cout << " <- head";
            if (i == tail) std::cout << " <- tail";
            if (i == current) std::cout << " <- current";
            std::cout << "\n";
        }
    }
    /*
    ### END SOLUTION
    */
};

// test
{
    UndoRedoCounter c1(10);   
    UndoRedoCounter c2=std::move(c1);
    cout << "c1:\n";
    c1.print_history();
    cout << "c2:\n";
    c2.print_history();
}
{
    UndoRedoCounter c1(10), c2;
    c2=std::move(c1);
    cout << "c1:\n";
    c1.print_history();
    cout << "c2:\n";
    c2.print_history();
}
/* Expect
c1:
History Buffer [size=0]:
c2:
History Buffer [size=5]:
[0] 10 <- head <- tail <- current
[1] 0
[2] 0
[3] 0
[4] 0
c1:
History Buffer [size=0]:
c2:
History Buffer [size=5]:
[0] 10 <- head <- tail <- current
[1] 0
[2] 0
[3] 0
[4] 0
*/
c1:
History Buffer [size=0]:
c2:
History Buffer [size=5]:
[0] 10 <- head <- tail <- current
[1] 0
[2] 0
[3] 0
[4] 0
c1:
History Buffer [size=0]:
c2:
History Buffer [size=5]:
[0] 10 <- head <- tail <- current
[1] 0
[2] 0
[3] 0
[4] 0