There are two ways to build a new class out of one you already have.
You will do both with the NumberList class from Lab 11. Along the way you will see the order in which
constructors and destructors run when one class contains or extends another, and you will meet one behavior
of inheritance that surprises nearly everyone the first time. The last task returns to the list itself and
walks it a different way: recursively.
Start by copying NumberList.h and NumberList.cpp from your Lab 11 directory into a new one, with a fresh
main.cpp. Keep the copy constructor and nodesAlive; both are used below. Delete addSorted from the
class. In Task B a sorted list gets a better home.
Write a class GradeBook in GradeBook.h and GradeBook.cpp:
class GradeBook
{
private:
string course;
NumberList scores;
public:
GradeBook(string course);
void addScore(double score);
double average() const;
void display() const;
};
A constructor can set its members before its body runs, in a member initializer list placed between
the parameter list and the opening brace:
GradeBook::GradeBook(string course)
: course(course)
{
}
Each entry member(expression) initializes one member. Inside the parentheses, the name means the
parameter; outside, before the parenthesis, it can only mean a member. So course(course) needs no
this->. Rewrite NumberList() the same way, as : head(nullptr) with an empty body. For members like
these, assigning in the body would work just as well; in Task C you will meet the case where only the
initializer list will do.
addScore adds to scores; average returns the mean of the scores, or 0 when there are none; display
prints the course name, a colon, and the scores. Each of the three is one or two lines, because NumberList already does the work. That is the point
of composition: GradeBook reuses the list without knowing anything about nodes.
Do not write a destructor for GradeBook. It never calls new, so it has nothing of its own to delete.
Yet it owns three nodes. Who frees them?
Find out with the counter. Create a GradeBook inside a pair of braces, add three scores, and print
NumberList::getNodesAlive() inside the braces and again after them:
CSCI 135: 88 72 95
Average: 85
Nodes alive inside: 3
Nodes alive after: 0
When an object is destroyed, the destructor of each of its members runs automatically, after the object’s
own destructor (here, the empty one the compiler supplied). scores is destroyed, ~NumberList runs, and
the nodes are freed. Explain this in a comment in main.cpp, in your own words.
The Lab 8 version kept the list sorted with a second member function. The textbook’s version is a separate
class, SortedNumberList, that inherits from NumberList and replaces add with its own:
#include "NumberList.h"
class SortedNumberList : public NumberList
{
public:
SortedNumberList();
SortedNumberList(double first);
void add(double number);
void displayList() const;
};
: public NumberList makes NumberList the base class and SortedNumberList the derived class.
Every member of the base is now also a member of the derived class: remove, size, sum, contains,
getNodesAlive, and head itself. You write only what is new or different.
Put this in SortedNumberList.h and SortedNumberList.cpp. For add, move in your old addSorted code,
renamed. A derived class that declares a member function with the same name and parameters as the base
class’s overrides it: calling add on a SortedNumberList now runs the sorted version.
Your add has to reach head and create ListNodes, and it can, because Lab 8 made them protected.
Change protected to private in NumberList.h and compile SortedNumberList.cpp to see what that
word has been doing:
SortedNumberList.cpp:17:9: error: 'NumberList::ListNode* NumberList::head' is private within this context
A private member is reachable only by the class’s own member functions; a protected one, also by its
derived classes’. Change it back.
displayList should print (sorted) and then the list. Do not copy the base class’s loop. Call the base
version explicitly, by its full name:
void SortedNumberList::displayList() const
{
cout << "(sorted) ";
NumberList::displayList();
}
Without the NumberList::, the call would mean this same function, and it would call itself forever.
A SortedNumberList contains a complete NumberList inside it, so creating one runs two constructors.
The base class’s runs first, then the derived class’s. Destruction goes in the opposite order: derived first,
base last. Each layer is built on top of a finished foundation and removed before that foundation is.
First give NumberList a second constructor, one that starts the list with a single value:
NumberList(double first);
Its whole job fits in the initializer list: head starts as a pointer to a new node holding first, and the
body stays empty.
By default the base part of a derived object is built with the base’s default constructor. To choose
another, name it in the derived constructor’s initializer list. This is the case where nothing else will do:
SortedNumberList::SortedNumberList(double first)
: NumberList(first)
{
}
Write both SortedNumberList constructors this way.
Now watch the order. Add a temporary cout line to both constructors of each class and to
~NumberList, and give SortedNumberList a temporary destructor that prints too. Then create a
SortedNumberList inside a pair of braces:
NumberList constructor
SortedNumberList constructor
--- the list exists ---
SortedNumberList destructor
NumberList destructor
Next, create one with new, keep its address in a pointer to the base class, and delete it through that
pointer:
NumberList *q = new SortedNumberList(1.0);
delete q;
Look at which destructors run. Then make the base destructor virtual:
virtual ~NumberList();
and run it again. Without virtual, delete q runs only ~NumberList — the derived part is never
destroyed, and the compiler gives no warning. With virtual, both run, in the right order. Any class
that others may inherit from, and that has a destructor, should make it virtual.
Record both outputs in a comment in main.cpp, keep the virtual, and remove the temporary prints.
Build a sorted list and add some values to it, out of order:
SortedNumberList sorted(7.9);
sorted.add(12.6);
sorted.add(2.5);
sorted.add(10.5);
sorted.displayList();
A pointer to a base class may hold the address of a derived object: every SortedNumberList is a
NumberList. So this compiles:
NumberList *p = &sorted;
p->add(5.0);
Display sorted again, and also display it through p. Predict the output before running it.
(sorted) 2.5 7.9 10.5 12.6
after p->add(5.0): (sorted) 2.5 7.9 10.5 12.6 5
through the pointer: 2.5 7.9 10.5 12.6 5
The 5 went at the end, and the (sorted) prefix disappeared. Through p, both calls ran the
NumberList versions.
The compiler chooses which add to call while it compiles, and at that moment all it knows is the
type of the expression: p is a NumberList *. It does not know, and does not check, what kind of
object p will point to when the program runs. The type of the expression decides, not the object.
So the sorted list is no longer sorted, and nothing in the language stopped it. Explain in a comment
why the 5 ended up last, and why calling sorted.add(5.0) directly would not have done that.
C++ can make the object decide, with virtual functions, the mechanism behind the
virtualdestructor
you wrote in Task C. That is the subject of Chapter 15, which this course does not cover. Here, the rule is
simpler: if you want the derived behavior, call through the derived type.
Every traversal so far has been a loop. A linked list also has a recursive shape: a list is either empty, or
a first node followed by a shorter list, the one that starts at next. So its length is 0 when it is
empty, and otherwise 1 plus the length of the rest. That sentence is already a recursive function.
A recursive function needs a parameter that shrinks with each call, and size() has none. The usual
answer is a pair: the public function the user calls, and a private helper that takes the node to start
from and does the recursion.
private:
int sizeFrom(ListNode *node) const;
public:
int size() const; // returns sizeFrom(head)
int NumberList::sizeFrom(ListNode *node) const
{
if (node == nullptr)
{
return 0;
}
return 1 + sizeFrom(node->next);
}
The nullptr test is the base case, an empty list; the call on node->next is the recursive case,
which moves one node closer to it. Leave out the base case and the recursion never stops.
Rewrite size this way, then sum with a helper sumFrom. Your Lab 11 tests must give the same answers.
The helpers are private because nobody outside the class should be handing out node pointers.
Now one that a loop cannot do easily. Add displayBackward(), which prints the list from last node to first.
The links only go forward, but recursion can wait: its helper prints the rest of the list backward first,
and only then prints the current node. Swap those two lines and you have displayList again.
2.5 7.9 12.6
12.6 7.9 2.5
size 3, sum 23
A SortedNumberList inherits all of this, so calling displayBackward on one prints it in descending order,
with no new code.
Then find the limit. Build a SortedNumberList of 1,000,000 nodes by adding the values from 1,000,000
down to 1 (each lands at the front, so this is fast). Call contains, which still uses a loop, and then
size. The loop finishes; the recursion crashes with Segmentation fault. Under the address sanitizer the
report names the cause:
ERROR: AddressSanitizer: stack-overflow
Every call that has not yet returned keeps its own frame on the stack, and a million of them do not fit.
Explain in a comment why the loop has no such limit, and which of the two you would use for a list
whose length you do not control. This is the trade-off from section 14.9.
Derive a class UniqueSortedList from SortedNumberList. It overrides add so that a value already in the
list is ignored, and is otherwise added in order. Its add is two lines: use the contains it inherited
from NumberList, and do the insertion by calling SortedNumberList::add. Do not touch head.
Add 3, 1, 3, 2, 1 and display the list:
(sorted) 1 2 3
That is three levels of inheritance, and UniqueSortedList gets displayList from the middle one.
Submit the seven source files:
NumberList.h NumberList.cpp
SortedNumberList.h SortedNumberList.cpp
GradeBook.h GradeBook.cpp main.cpp
If you did the bonus, put UniqueSortedList in SortedNumberList.h and SortedNumberList.cpp.
main.cpp should contain your comments and recorded outputs from Tasks A, C, D and E. Do not submit compiled
executables. Each file should start with a comment containing your name and a short description, for
example:
/*
Author: your name
Course: CSCI-135
Instructor: their name
Assignment: Lab 12
Here, briefly, at least in one or a few sentences
describe what this file contains.
*/