C++ Copy Constructors


Once you start building objects that connect to other objects, creating a copy of an object becomes much more complicated. If we think of the object as a simple container like this:


Making a copy of this is easy. We just create a new chunk of memory, and copy into that container the values currently in the original object box. This can be done by just copying in all the bits.

However, if the object contains pointers to other objects, then making a simple copy gives us something we do not expect:


This is not what we want. the object we are thinking of here is a “list”, and we want a copy of the entire list, not just one part of it!

This picture shows what is going on when we do a copy of a complex data structure:

Obviously, we want the “deep copy” for most purposes.

Copy Constructors

If you do not write one of your own, the compiler will build a copy constructor for you. This default one does the simple copy operation, which is fine for many simple classes.

We need to create something called a “deep copy” of the object, meaning we copy not just the base object itself, but all the other objects that base object points to!

Creating an exact copy of our linked list is much easier if we add one additional pointer to the class. This one will be used to track the end of the list. Here is the basic idea:

LinkedList::LinkedList(const LinkedList & src); {
    Node *node = src.head;
    while (node != nullptr) {
        node = node->next;

Here, we have captured all the logic needed to build a new node in the addTail method.

Class Destructors

If we build such a “deep copy”, we probably want to set up a way to destroy the copy as well.

LinkedList::~LinkedList() {
    while (Head != nullptr) {
        Node *temp = head;
        delete temp;

Thid code uses the remove method to delete nodes from the list.