Copy Constructor question

I have a class that contains pointers to instances of the same class as attributes. How would a copy constructor look for this. I understand that I may not be able to use the implicit copy constructor due to these pointers.

Code Follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Node
{
   public:
      int key;
      Node *parent;
      Node *leftChild;
      Node *rightChild;
      Node();
      ~Node();
};
Node::Node()
{
   key=rand();
}

Node *aNode=new Node();
Node *anotherNode=new Node(*aNode);//does this work to copy the node including its pointers??

//could I point the pointers to new Node objects? 
The implicit copy constructor will set the value of *parent and such to the exact same address as the object you're copying from. So the copied and the initial parent and children will point to the same objects.

This is dangerous, because if you're pointing to the same object through more than one pointer a change can come from any one of those, and sometimes you can't predict what's going to change what.

If you want *parent and so on to point to their own new objects, or something like NULL you'll need to write your own copy constructor.
Last edited on
Something like this:
1
2
3
4
5
6
7
8
9
10
Node::Node(Node &aNode)
{
      key=aNode.key;
      parent=NULL;
      leftChild=NULL;
      rightChild=NULL;
}

//then i can point the parent etal. to whatever node I want...or assign new nodes...is this correct?


Thanks
Yeah, pretty much. You should probably take aNode by const reference though since you aren't modifying it.
Great...thanks a bunch.

Node::Node(const Node &aNode)
Topic archived. No new replies allowed.