MitchellT
MitchellT

Reputation: 77

Binary Tree - Copy Constructor

I am trying to create a copy constructor for my Binary tree.

My problem:

I can see the values of the source tree getting copied into the target tree but when it comes to writing the values out, there are no values in the copied tree and it crash's my program.

Error Message:

Unhandled exception at 0x0097a43c in binTree.exe: 0xC0000005: Access violation reading location 0xccccccec.

Code:

// Main Method

    int main(int argc, char **) {
    ifstream fin6("input_data.txt");
    ofstream out9("copied_tree.txt");

    if(!fin6.is_open()) 
    {
        cout << "FAIL" << endl;
        return 1;
    }

    BinaryTreeStorage binaryTreeStorage2;

    // read in values into data structure
    binaryTreeStorage2.read(fin6);

    BinaryTreeStorage binaryTreeStorage3 = binaryTreeStorage2;

    // output values in data structure to a file
    binaryTreeStorage3.write(out9);

    fin6.close();
    out9.close();

    // pause
    cout << endl << "Finished" << endl;
    int keypress; cin >> keypress;
    return 0;
}

// Copy Constructor

BinaryTreeStorage::BinaryTreeStorage(BinaryTreeStorage &source)
{
    if(source.root == NULL)
        root = NULL;
    else
        copyTree(this->root, source.root);
}

// Copy Tree Method

void BinaryTreeStorage::copyTree(node *thisRoot, node *sourceRoot)
{
    if(sourceRoot == NULL)
    {
        thisRoot = NULL;
    }
    else
    {
        thisRoot = new node;
        thisRoot->nodeValue = sourceRoot->nodeValue;
        copyTree(thisRoot->left, sourceRoot->left);
        copyTree(thisRoot->right, sourceRoot->right);
    }
}

Upvotes: 3

Views: 21283

Answers (1)

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76808

If you change the value of a pointer (not the pointee) in a function, you have to pass a reference to that pointer:

void BinaryTreeStorage::copyTree(node *& thisRoot, node *& sourceRoot)

If you pass a pointer into a function, this pointer is passed by value. If you change the value of the pointer (the address it stores), this change is not visible outside the function (this is what happens when you call new). So, to make the change visible outside the function, you have to pass a reference to the pointer you want to modify.

This question explains it in detail.

Upvotes: 3

Related Questions