Search code examples
c++treecopy-constructordeep-copy

Why does the Copy Constuctor fail to "copy"


I am trying to better understand copy constructors.

When I create a new instance of the private values within the copy constructor,it should be different from the initial value.

However, this is not the case. I am not assigning the values via a reference and neither am I assigning a pointer, yet when I look at the debugger, the memory locations remain unchanged.

What is the 'new' doing if the resulting action remains the same?

// copy control within a template
NTree(const NTree& aOtherNTree)
{
    fKey = new T;
    fNodes[N] = new NTree<T, N>;

    fKey = aOtherNTree.fKey;
    for (int i = 0; i < N; i++)
    {
        fNodes[i] = aOtherNTree.fNodes[i];
    }

Full Code

#pragma once

#include <stdexcept>

#include "TreeVisitor.h"
#include "DynamicQueue.h"

template <class T, int N>
class NTree {
private:
    const T* fKey; // 0 for empty NTree
    NTree<T, N>* fNodes[N]; // N subtress of degree N

    NTree(); // sentinel constructor

public:
    static NTree<T, N> NIL; // sentinel

    NTree(const T& aKey); // a simple NTree with key and N subtrees of degree N

    bool isEmpty() const; // is tree empty
    const T& key() const; // get key (node value)

    // indexer (allow for result modification by client - no const in result)
    NTree& operator[](unsigned int aIndex) const;

    // tree manipulators (using constant references)
    void attachNTree(unsigned int aIndex, const NTree<T, N>& aNTree);
    const NTree& detachNTree(unsigned int aIndex);

    // depth-first traversal
    void traverseDepthFirst(const TreeVisitor<T>& aVisitor) const;

    // copy control
    NTree(const NTree& aOtherNTree)
    {
        fKey = new string;
        fNodes[N] = new NTree<string, N>;

        fKey = aOtherNTree.fKey;
        for (int i = 0; i < N; i++) {
            fNodes[i] = aOtherNTree.fNodes[i];
        }
    }

    ~NTree()
    {
        for (int i = 0; i < N; i++) {
            if (!isEmpty()) {
                if (!fNodes[i]->isEmpty()) {
                    delete fNodes[i];
                }
            }
        }
    }

    NTree& operator=(const NTree& aOtherNTree)
    {
        fKey = new T;
        fNodes[N] = new NTree<T, N>;

        fKey = aOtherNTree.fKey;
        for (int i = 0; i < N; i++) {
            fNodes[i] = aOtherNTree.fNodes[i];
        }

        return *this;
    }

    // breadth-first traversal
    void traverseBreadthFirst(const TreeVisitor<T>& aVisitor) const
    {
        DynamicQueue<const NTree<T, N>*> lQueue;
        lQueue.enqueue(this);

        while (!lQueue.isEmpty()) {
            const NTree<T, N>& head = *lQueue.top();
            lQueue.dequeue();

            aVisitor.visit(head.key());

            for (int i = 0; i < N; i++) {
                if (head.fNodes[i]->fKey != NULL) {
                    lQueue.enqueue(&head[i]);
                }
            }
        }
    }
};

// implementation

template <class T, int N>
NTree<T, N> NTree<T, N>::NIL;

// sentinel constructor
template <class T, int N>
NTree<T, N>::NTree()
{
    fKey = (T*)0;
    for (int i = 0; i < N; i++)
        fNodes[i] = &NIL;
}

// node constructor
template <class T, int N>
NTree<T, N>::NTree(const T& aKey)
{
    fKey = &aKey;
    for (int i = 0; i < N; i++)
        fNodes[i] = &NIL;
}

// isEmpty
template <class T, int N>
bool NTree<T, N>::isEmpty() const
{
    return this == &NIL;
}

// key
template <class T, int N>
const T& NTree<T, N>::key() const
{
    if (!isEmpty())
        return *fKey;
    else
        throw std::domain_error("Empty NTree.");
}

// indexer
template <class T, int N>
NTree<T, N>& NTree<T, N>::operator[](unsigned int aIndex) const
{
    if (isEmpty())
        throw std::domain_error("Empty NTree!");

    if (aIndex < N && fNodes[aIndex] != &NIL) {
        return *fNodes[aIndex]; // return reference to subtree
    }
    else
        throw std::out_of_range("Illegal subtree index!");
}

// tree manipulators
template <class T, int N>
void NTree<T, N>::attachNTree(unsigned int aIndex, const NTree<T, N>& aNTree)
{
    if (isEmpty())
        throw std::domain_error("Empty NTree!");

    if (aIndex < N) {
        if (fNodes[aIndex] != &NIL)
            throw std::domain_error("Non-empty subtree present!");

        fNodes[aIndex] = (NTree<T, N>*)&aNTree;
    }
    else
        throw std::out_of_range("Illegal subtree index!");
}

template <class T, int N>
const NTree<T, N>& NTree<T, N>::detachNTree(unsigned int aIndex)
{
    if (isEmpty())
        throw std::domain_error("Empty NTree!");

    if ((aIndex < N) && fNodes[aIndex] != &NIL) {
        const NTree<T, N>& Result = *fNodes[aIndex]; // obtain reference to subtree
        fNodes[aIndex] = &NIL; // set to NIL
        return Result; // return subtree (reference)
    }
    else
        throw std::out_of_range("Illegal subtree index!");
}

template <class T, int N>
void NTree<T, N>::traverseDepthFirst(const TreeVisitor<T>& aVisitor) const
{
    // visit every subtree (no invisit)
    if (!isEmpty()) {
        aVisitor.preVisit(key());
        for (unsigned int i = 0; i < N; i++) {
            fNodes[i]->traverseDepthFirst(aVisitor);
        }
        aVisitor.postVisit(key());
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////

#include "NTree.h"

Solution

  • Not sure what memory addresses you are referring to, but contrary to your claim "neither am I assigning a pointer", your code does in fact assign a pointer. Many of them, in fact. That's pretty much all it does, is assign pointers. First here:

    fKey = new T;
    

    That's a pointer assignment. So is this:

    fNodes[N] = new NTree<T, N>;
    

    That one also happens to be an assignment to an out of bounds element of an array. That is, fNodes is an array of N pointers, fNodes[N-1] is the last element (pointer) in that array, and fNodes[N] is out of bounds.

    This is also a pointer assignment:

    fKey = aOtherNTree.fKey;
    

    It is also a memory leak, since you've now written over the value that was returned from the call to new T earlier in the function. And so have no access to, and no way to deallocate that object.

    Then finally, your for loop consists of N pointer assignments.

    for (int i = 0; i < N; i++)
    {
        fNodes[i] = aOtherNTree.fNodes[i];
    }
    

    You are simply copying the pointers from aOtherNTree.fNodes to fNodes.