
-----------------------------------
divad12
Tue Apr 01, 2008 10:46 am

Copying classes with pointers
-----------------------------------
How would I make a deep copy of an object which has properties that are pointers? If I just use the copy operator (=), the pointers would still point to the same memory location. 

Essentially I have a class which contains instances of the Node class. The Node class looks something like this:


class Node
{
public:
    vector   next;
    vector   prev;
    /* ... */
};


and the class which contains it looks something like this:


class Circuit
{
public:
    vector  gates;
    /* ... */
};


I wish to copy an instance of the Circuit class, but without having Circuit::gates all point to the same node locations as the original object. Is there a way to do this in C++?

Thanks.

-----------------------------------
md
Tue Apr 01, 2008 10:59 am

RE:Copying classes with pointers
-----------------------------------
Overwrite the copy operator and make copies of the data pointed to in your overloaded operator.

Something like  class Circuit
{
public...

 Circuit& operator=(const Circuit& to_copy)
{
...
return *this;
}

private:
...
};


-----------------------------------
divad12
Tue Apr 01, 2008 12:58 pm

Re: Copying classes with pointers
-----------------------------------
I would have to make new copies of the Node objects, but they contain pointers to each other. If I make new Node objects, they would still point to their older copies. How would I make them point to new copies? Should I use a recursive function? Do I have to completely reconstruct the Circuit?

-----------------------------------
md
Tue Apr 01, 2008 4:38 pm

RE:Copying classes with pointers
-----------------------------------
You would have to duplicate the node list, yes. How you do that is entirely up to you.

-----------------------------------
OneOffDriveByPoster
Wed Apr 02, 2008 12:15 pm

Re: Copying classes with pointers
-----------------------------------
If am not too sure (especially since the code is not complete), but it looks like you are keeping pointers to things in a vector and I do not think that is safe.  Unless if I am mistaken, there is no guarantee that the address of the vector elements will remain the same when you modify the vector.
