I am handling a binary search tree data structure and I am arrived at the implementation of the copy semantics. Since I want to do a deep copy, I decided to create a new object inside the copy assignment and then to pass it outside the function. However when I invoke a copy assignment nothing is done on the variable of the object that I want to change. What am I doing wrong? I assume that there is an error in the definition of the keywords in the operator overload.
// copy assignment -- deep copy
bst operator=(const bst& bintree){
std::cout<<"copy assignment invoked"<<std::endl;
bst newbst{};//here I create a new object, so I am sure it is a deep copy
newbst.insert(bintree.root->value);//I add the root first
copy_part(bintree.root, newbst);//then I add the remaining nodes
return newbst;
}
void copy_part(Node<treepair>* x, bst& bintree){
if(x->left!=nullptr){
bintree.insert(x->left->value);
copy_part(x->left,bintree);
}
if(x->right!=nullptr){
bintree.insert(x->right->value);
copy_part(x->right,bintree);
}
}
...
int main(){
bt_INT bintree{};
/*
here i fill bintree
*/
bt_INT bintree_copy{};//made an empty tree
bintree_copy = bintree;//copy assignment
//however if i print bintree_copy it gives me an empty array.
// what am I missing here?
}
Notice that in the definition of the operator= I did not write bst& because I had to return a local variable.
EDIT: I am reading your comments and I made a few changes
class bst{
...
bst& operator=(const bst& bintree){
(*this).clear();//I clear the nodes present in the LHS of the assignment
(*this).insert(bintree.root->value);//I insert the root first
copy_part(bintree.root, *this);
return *this;
}
void copy_part(Node<treepair>* x, bst& bintree){//I left this part since I need to perform a deep copy
if(x->left!=nullptr){
bintree.insert(x->left->value);
copy_part(x->left,bintree);
}
if(x->right!=nullptr){
bintree.insert(x->right->value);
copy_part(x->right,bintree);
}
}
...
};
Now it works fine. Now I just have to cope with the copy constructor.