this, const, static, and CopyingIn Lab 8 you built NumberList, a linked list wrapped in a class. It works, but it has three weaknesses,
and this lab removes them one at a time.
value1 and next1, because the obvious names wereStart by copying NumberList.h, NumberList.cpp and main.cpp from your Lab 8 directory into a new one.
Everything below modifies that class. You may drop the bonus reverse function if you wrote it; nothing here
needs it.
Lab 8’s node constructor reads like this:
ListNode(double value1, ListNode *next1 = nullptr)
{
value = value1;
next = next1;
}
Rename the parameters to value and next. Now value = value; assigns the parameter to itself and
leaves the member untouched — the parameter hides the member, because the innermost name wins.
Every member function has a hidden parameter called this: a pointer to the object the function was
called on. this->value always means the member, whatever else is in scope:
ListNode(double value, ListNode *next = nullptr)
{
this->value = value;
this->next = next;
}
That is the most common reason to write this explicitly. Make the change, and confirm your Lab 8 tests
still pass.
Add three member functions to NumberList:
int size() const; // how many nodes
double sum() const; // total of all values
bool contains(double number) const; // is this value present?
The const after the parameter list is a promise: this function will not modify the object it was called
on. Inside it, this points to a constant object, so any assignment to a member is a compile error.
displayList was already declared this way in Lab 8; now you know why.
Each of the three is a traversal, the loop you have written many times. Use a separate pointer to walk the
list; never move head itself.
Then break the promise on purpose. Inside sum, add the line head = nullptr; and compile. Read the
error, then remove the line. Next, try calling a non-const member function such as add from inside
size. That fails too: a const function may only call other const functions, since otherwise it could
change the object at one remove. Section 11.1 calls this const has to be consistent.
An ordinary member variable belongs to one object; ten lists have ten head pointers. A static member
variable belongs to the class itself, and exists exactly once however many objects there are.
Add a counter of live nodes:
class NumberList
{
protected:
class ListNode { ... };
ListNode *head;
static int nodesAlive; // declaration: one copy, shared by every list
public:
static int getNodesAlive();
...
};
A static member is only declared inside the class. It must also be defined, exactly once, in
NumberList.cpp — this is where its storage is created:
int NumberList::nodesAlive = 0;
Leave that line out and the program compiles but fails to link, with an undefined reference to
NumberList::nodesAlive. Try it.
Make the nodes count themselves. Add nodesAlive++; to the ListNode constructor, and give ListNode a
destructor containing nodesAlive--;. A nested class may use the enclosing class’s members, so the name
works there as written. Now every node, however and wherever it is created or deleted, keeps the count
correct.
getNodesAlive is a static member function. It is called through the class rather than an object:
cout << NumberList::getNodesAlive() << endl;
Because no object is involved, a static function has no this, and so it cannot touch head or any other
ordinary member. It can only reach static ones.
Print the count at the start of main, after building a list, and after the list goes out of scope. It
should read 0, then the number of nodes, then 0 again. That last 0 is your destructor being
checked for you.
When you do not write one, the compiler supplies a copy constructor for you. It copies the object
memberwise: each member of the new object is set to the corresponding member of the old one. For
NumberList that means one member, head, and so one pointer.
Memberwise copying happens in two places, and they look different but do the same thing:
NumberList b(a); // initialization: the copy constructor runs
NumberList c;
c = a; // assignment: memberwise assignment runs
Write a short test that builds a three-node list a, then makes b from it with NumberList b(a);, all
inside a pair of braces so both lists are destroyed at the closing brace. Print nodesAlive after the copy
and again after the braces.
The count after the copy is 3, not 6. Your counter has just shown you the bug: no nodes were
copied, only the address of the first one. Then the program dies at the closing brace:
Nodes alive after copy: 3
free(): double free detected in tcache 2
Aborted
Build it again with -fsanitize=address and the report is heap-use-after-free: the second destructor
read a node’s next after the first destructor had already freed it.
Repeat the experiment with assignment, c = a; instead of the copy constructor. The result is the same,
and for the same reason. Record both outputs in a comment in main.cpp, then remove the test code so
the program runs again.
Write a copy constructor that builds a second chain, node for node:
NumberList(const NumberList &other);
Walk other’s list and create a new node for each value, appending in order. The simplest correct way is
to start with head = nullptr; and call add once for each value.
The parameter has to be a reference. If it were passed by value, then passing it would require a copy,
which would call the copy constructor, which would need a copy of its parameter, and so on until the
program runs out of stack. The compiler refuses to accept that version. It is const because copying does
not change the original.
Run the Task D test again. Now the count after the copy is 6, the program survives the closing brace, the
count returns to 0, and the sanitizer is silent. Then show the copies are independent: add a value to b
and print both lists. Only b changes.
The copy constructor is also called for you, without any copy being written in your code. Write a
function that takes a list by value:
void showByValue(NumberList list);
and print nodesAlive inside it. The count rises by the list’s size for as long as the function runs,
because passing by value constructed a whole new copy. Passing by const reference copies nothing, which
is why you have been told to do it since Lab 5.
Nodes alive at start: 0
a: 2.5 7.9 12.6
size 3, sum 23, contains 7.9? yes
Nodes alive: 3
a: 2.5 7.9 12.6
b: 2.5 7.9 12.6 99
Nodes alive after copy: 7
Inside showByValue, nodes alive: 10
Nodes alive after call: 7
Nodes alive at end: 0
Now rerun the assignment test from Task D, c = a;. It still crashes. Your copy constructor handles
initialization, but assignment is a separate operation, and it is still memberwise.
The 17.d lecture called this the Rule of Three: a class that needs a hand-written destructor almost
always needs a hand-written copy constructor and a hand-written assignment. Writing the third one requires
operator overloading, which is not part of this course. So, for now, the rule for you is plain: never
assign one NumberList to another. Copy-construct instead.
If your copy constructor calls add for each node, it is correct but slow. Every add walks the entire new
list to find its end, so copying n nodes takes about n² / 2 steps.
Rewrite it to keep a tail pointer to the last node created, so each new node is attached in one step.
Be careful with the first node, which has no predecessor and has to become head instead.
Then measure. Build a 40,000-node list in a single pass by inserting each value at the front, copy it, and
run the program under the shell’s time command, once with each version. On our machine the add-based
copy takes about 1.5 seconds and the tail-pointer copy about 5 milliseconds — the difference between
n² and n, made visible. Your timings will differ; the ratio should not.
Submit the three source files:
NumberList.h NumberList.cpp main.cpp
main.cpp should contain your recorded outputs from Task D as comments, and should run to completion
without crashing. 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 11
Here, briefly, at least in one or a few sentences
describe what this file contains.
*/