Re: tree copy constructor...
Quote:
Originally Posted by georgi0u
can anyone see any issues with this copy constructor for a binary tree data structure...
Before anything, have you used the debugger to see what your problems may be?
Second:
Code:
TreeNode<T>* copy_tree( TreeNode<T>* old_root )
This is not a copy constructor. It is function called copy_tree(). Please show your true copy constructor. If it calls copy_tree(), still show the real copy constructor.
Third, implementing a copy constructor means you should implement a user-defined assignment operator and proper destructor. Did you do that?
Regards,
Paul McKenzie
Re: tree copy constructor...
i did do that...
sorry i didn't post this before.
Code:
template <class T>
class cs2set {
public:
typedef tree_iterator<T> iterator;
private:
TreeNode<T>* root_;
int size_;
public:
cs2set() : root_(0), size_(0)
{}
cs2set( const cs2set<T>& old ) : size_(old.size_) {
this ->destroy_tree(root_);
root_ = this -> copy_tree( old.root_,0 );
}
~cs2set() {
this -> destroy_tree( root_ );
root_ = 0;
}
anyway im posting this for future referance because i already figured it out. The problem was with the way i was dealing with node parents...
heres the revised working version of what my copy constructor calls....
Code:
TreeNode<T>* copy_tree( TreeNode<T>* old_root,TreeNode<T>* tempparent ) {
if(!old_root) return 0;
TreeNode<T> *p = new TreeNode<T>;
p->value = old_root->value;
p->parent = tempparent;
if(old_root->left)
p->left = copy_tree(old_root->left,p);
if(old_root->right)
p->right = copy_tree(old_root->right,p);
return p;
}
Re: tree copy constructor...
Quote:
Originally Posted by georgi0u
Anyway im posting this for future referance because i already figured it out. The problem was with the way i was dealing with node parents...
You still didn't code an assignment operator. If not, your program will not be able to do this correctly:
Code:
int main()
{
TreeNode<int> T1;
TreeNode<int> T2;
T1 = T2; // no good
}
When coding a copy constructor, it always goes with an assignment operator. The reason why is that C++ programmers who expect this to work:
Code:
TreeNode<int> T1;
TreeNode<int> T2 = T1; // copy constructor called
Also expect this to work:
Code:
TreeNode<int> T1;
TreeNode<int> T2;
T1 = T2;
since both are natural means of assigning and constructing objects.
Regards,
Paul McKenzie