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 privateMotivation¶
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:
The backward counter has the default constructor deleted using the
deletekeyword; andthe
operator()callsset_countto decrement thecount.
Solution to Exercise 1
The changes are due to the following reasons:
There is no meaningful single default value to start the count down.
The count will eventually be decreased to 0 so
set_countcan ensure thecountdoes 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.
publicmember specifier (public inheritance) for a base class means the access to the members of the base class is also inherited.protectedmember specifier (protected inheritance) means thatpublicmembers of the base class becomeprotected.privatemember specifier (private inheritance) means that both thepublicandprotectedmembers of the base class becomeprivate.
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).
The access specification follows that of the base class, not the accessibility of the using-declaration. E.g., while using Counter::Counter is not declared with public member access, the inherited constructor explicit Counter(int count) : count{count} {} has public access.
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
Unfortunately, the above code does not work properly. Why?
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;
}
};For any class that is meant to be inherited, it is a good practice to make the destructor
public and virtual so that it can be properly overriden by the derived class to clean up the resources of the derived class; or
protected and non-virtual so that the base class cannot be used for destruction.
Why not make the constructor public and virtual so the derived classes can override it?
Virtual constructor is not allowed in C++:
// error: constructor cannot be declared 'virtual'
virtual explicit Counter(int count=0) : count{count} {}%%hermes
Explain in a paragraph why virtual constructor is not allowed in C++.🌿 Fork/new: main (will create on click)
Hermes
A virtual function only works because the object already exists: dispatch happens at runtime by following the vtable pointer stored inside the object to find the right override — but a constructor runs on memory that has just been allocated, before any subobject or vtable pointer is in place (the constructor itself is what sets the vtable pointer to point at the class being built). So a “virtual constructor” would have to be dispatched through the very mechanism it is responsible for creating — a chicken-and-egg problem. There is also a sizing problem: new Counter must reserve exactly sizeof(Counter) bytes at compile time, so a runtime choice of “which” constructor runs could never change how much memory gets allocated; and unlike member functions, constructors are not inherited at all — BackwardCounter above defines its own explicit BackwardCounter(int count) that delegates to Counter(count) — so there is no base version for a derived constructor to override in the first place. For this reason C++ forbids it outright (g++ rejects the lecture’s attempted line with error: constructors cannot be declared 'virtual'), and offers the two working alternatives instead: a virtual destructor — which can work because during destruction the object still fully exists with a valid vtable, hence virtual ~Counter() = default; above for safe polymorphic deletion — and factory functions (e.g. a static factory or abstract factory returning unique_ptr<Counter>) to achieve polymorphic creation.
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.
override?It is optional but good practice to add the override qualifier to let the compiler know it is intended to override the base version. If the compiler cannot find a base version with the same signature, which may happen due to typos, the compiler will raise an error instead of creating a new overload.
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?↻ Session: main (ACP: 15890faf-575…)
Hermes
How: A virtual call is not compiled into a direct jump to a fixed address the way an ordinary (statically bound) call is. Instead, every class with at least one virtual function gets its own vtable — a per-class array of function pointers, one slot per virtual function — and every polymorphic object carries a hidden vptr, a pointer to its own class’s vtable, which the constructor sets up. The emitted code for (*counter2)() above is therefore: load the object’s vptr, index operator()'s slot in that table, and jump through the pointer found there. Since counter1 is actually a BackwardCounter, its vptr points at BackwardCounter’s vtable, so both loops in the cell above end up calling BackwardCounter::operator() even though counter2/counter3 have static type Counter. The price is one extra pointer load plus an indirect call per virtual call, and one hidden word per polymorphic object — I verified the layout with g++: two otherwise identical single-int classes measure sizeof == 4 vs sizeof == 16 once the method becomes virtual (8 bytes for the vptr, 4 more from alignment padding).
Why “virtual”: because which function is invoked is deliberately left undecided at compile time and resolved at run time from the object’s dynamic type. An ordinary function’s target address is fixed when the program is built (static binding); a virtual function’s target is only known once you look inside the live object, so its binding is “virtual” — dynamic/indirect rather than concrete. The name captures exactly this contrast with static dispatch: the compiler emits one generic calling routine and delegates the choice of actual function body to the run-time lookup through the object’s vptr.
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.
Explain whether *counter2 and counter3 of type BackwardCounter counts backward.
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
Why doesn’t vector<Counter> allow polymorphism?
vector<Counter> allow polymorphism?The issue is that BackwardCounter(3) is sliced down to a Counter object when copied/moved/cast to Counter, as illustrated in the following code.
%%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.
counter2 is said to be accessed through its base class pointer, which only reinterpret but not modify the object it points to.
How to avoid giving names to each element? Modify the code to create the counters in the heap.
%%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 scope1 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 automatically1 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 *bufferis a dynamically allocated array that stores the history of counter values.size_t historysizeis the size of the buffer.size_t headis the index of the most recent entry in the buffer.size_t tailis the index of the oldest entry still retained in the buffer.size_t currentis the index of the current value.The method
void print_history()prints the contents of the historybufferannotated with the position ofhead,tail, andcurrent.
Explain how int push(int value) works.
size_t after(size_t pos) constreturns the wrapped index afterpos.size_t before(size_t pos) constreturns the wrapped index beforepos.
Solution to Exercise 7
The function pushes value into the history buffer and return it:
If
headis right beforetailbefore the push, the buffer is full so thevaluewill overwrite the oldest value. Therefore, tail is updated to the index of the second oldest value.The
headandcurrentis updated to the index aftercurrent, where thevalueis 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 thecountdefault to0.The explicit constructor
explicit UndoRedoCounter(int count, int historysize=5)initializes private members as follows:The
countis initialized by reusing the base class constructorexplicit Counter(int count).Since the current count must be stored in the history as well, the constructor ensures
historysizeis at least 1 before allocating the memory forbuffer.currentis initialized to-1since it will be incremented to0bypush(count);.headandtailis initialized to0, which will be the position of the current count after the push.
The destructor
~UndoRedoCounter() overridereleases the memory allocated tobuffer. 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
Why not initialize head to -1 instead of 0?
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.
Explain how failing to declare the base‑class destructor ~Counter() as virtual can result in a memory leak when an UndoRedoCounter object goes out of scope.
Is ~UndoRedoCounter called when c goes out of scope?
{
Counter *c=UndoRedoCounter();
} // c goes out of scope. Is `~UndoRedoCounter` called?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()movescurrentback by one position if doing so does not exceed the tail, i.e., the conditioncurrent != tailreturned bycan_undo, andcountis then updated to the value of thebufferat thecurrentposition.
%%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 change0 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` times1 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()movescurrentforward by one position if doing so does not exceed the head, i.e., the conditioncurrent != headreturned bycan_redo, andcountis then updated to the value of thebufferat thecurrentposition.
%%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 change0 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 Why undo cannot be found even though the actual type of c defines it?
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?🌿 Fork/new: main (will create on click)
Hermes
Because Counter in the lecture is polymorphic — cell 71 gives it virtual ~Counter() = default; plus virtual operator() and set_count — the compiler can use run-time type information (RTTI) to answer “what is this object really?” at run time. In cell 93, unique_ptr<Counter> c { make_unique<UndoRedoCounter>() }; holds an UndoRedoCounter whose static type is only Counter, so c->undo() won’t compile: the compiler resolves names against the declared type. dynamic_cast<UndoRedoCounter*>(c.get()) asks for the dynamic type instead: if the pointed-to object is an UndoRedoCounter (or further derived from it), it performs the pointer adjustment needed to reach the derived subobject and returns a valid UndoRedoCounter*; if the object is merely some other Counter, it returns nullptr. That null-on-mismatch behavior is what makes it safe where static_cast would be undefined behavior — you can never end up calling a method that doesn’t exist on the object you point at. It also explains why the base must be polymorphic: with no vtable there is no run-time type to inspect, and the cast is rejected at compile time (error: cannot 'dynamic_cast' ... source type is not polymorphic).
The second half is what cell 97 does with the result. Since the cast can legitimately fail, its value must be checked (if (raw)) before use; once it succeeds, raw->undo() is legal because the pointer now has the derived type. The wrapping into unique_ptr<UndoRedoCounter> d(raw) plus c.release() is ownership bookkeeping, not part of the cast itself: after constructing d around the raw pointer, c must be told it no longer owns that object, otherwise both smart pointers would delete it and the program would double-free. I verified both sides with g++ (-std=c++23 -O2): casting through a matching base pointer yields a usable derived pointer (“ok, extra=42”), casting to a wrong sibling type yields null, and attempting the cast through a non-polymorphic base fails to compile with the diagnostic above.
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'; // 101 11 0 10
But the above is not a fix. There is an even bigger memory issue:
Execute the follow code:
{
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?
}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
Why is the history for c2 modified by the call c1() even though c2 is a separate copy?
c2 modified by the call c1() even though c2 is a separate copy?This is a mutation bug due to how the default copy constructor works:
The default constructor perform a shallow copy of the
bufferpointer, meaning both objects will point to the same memory.
Explains the crash.
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:
Delete the copy constructor if copying is not intended:
UndoRedoCounter(const UndoRedoCounter&) = delete;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
Counterpart 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
Why does the above code fail?
There is again a mutation bug because the default copy assignment operator for c2=c1 performs a shallow copy of the buffer.
Explain how the above code leads to memory leak.
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:
Delete the copy assignment operator if copying is not intended:
UndoRedoCounter& operator=(const UndoRedoCounter&) = delete;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
To allow code reuse between the copy constructor and assignment operator, add a private method void copy_from(const UndoRedoCounter& other) to handle buffer allocation and copying, which both the copy constructor and assignment operator can reuse.
%%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:
The Rule of Three states that if a class declares any one of the following, it should explicitly provide the other two as well:
A destructor
A copy constructor
A copy assignment operator
In other words, whenever you define one of these special member functions you should typically define all three to avoid subtle resource‑management bugs.
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
Why does the above code appear to run but c1 is not actually moved?
Hint
The default move constructor and the default move assignment operator are not explicitly declared. Will they be implicitly declared?
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::moveis treated as an rvalue that can be pass by constant lvalue reference to the copy constructor and copy assignment operator.
If a class needs a destructor, copy constructor, or copy assignment operator, it likely also needs a move constructor and move assignment operator for efficient transfer of temporary objects.
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
We can simplify UndoRedoCounter class by using standard containers like std::vector to manage the history buffer. This approach eliminates the need to manually define destructors, copy/move constructors, and assignment operators, allowing us to rely on the compiler-generated defaults. Complete the following code for such an implementation.
%%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
Make Counter an abstract base class by setting one or more of the virtual method to 0. Then implement ForwardCounter and BackwardCounter as the derived class of Counter, and UndoRedoCounter as the derived class of ForwardCounter.