0

I am trying to overload and assignment operator but the program keeps crashing here's what I have tried. Assignment operator overloaded on line 238.Code Any help is appriciated

  • 1
    `BinaryTree *newTree; newTree->insert(0);` What did you expect this would do? `newTree` is an indeterminate pointer that you dereference *immediately* after declaration. You shouldn't be using a pointer there at all, and I suggest you read up on [The Rule of Three/Five/Zero](https://en.cppreference.com/w/cpp/language/rule_of_three), as well as the [copy/swap idiom](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) – WhozCraig Nov 01 '18 at 02:35
  • @WhozCraig I want it to add a node to the TreeNode that is contained in the class isn't that what it's supposed to do? I have also just tried BinaryTree newTree; newTree.insert(0); but it doesn't work either. – CPlusJavaPlusZ Nov 01 '18 at 02:37
  • Do as I suggested, and read up from both links I posted previously. – WhozCraig Nov 01 '18 at 02:40
  • 1
    @CPlusJavaPlusZ *Trying to overload a Binary Search Tree assignment operator* -- I suggest you write the copy constructor first. Once you write the copy constructor, then the assignment operator is literally just a bunch of `std::swap`'s and a `return` statement. – PaulMcKenzie Nov 01 '18 at 03:10

1 Answers1

0

Honestly, you're probably lucky that the bug shows itself.

BinaryTree *newTree; newTree->insert(0);

Creates a pointer to BinaryTree which will point to nothing, and then you call dereference it with the -> operator which leads to undefined behavior in c++.

Assuming everything else about your function is correct (including the implementation of the other functions), then the correct way would be this based on your current code (notice the function returns a reference) :

BinaryTree & BinaryTree::operator=(const BinaryTree &myTree)
{
    this->insert(0);
    this->FillTree(*this, myTree.root);
    return *this;
}

BUT, I find it highly likely that there's other bugs in your code, and you should take the advice of other commenters and implement a copy constructor first.

samuelnj
  • 1,577
  • 7
  • 18