Re: copy construct
Jens Schmidt wrote:
exergy wrote:
Hello, if I have a class like this:
class Node{
private:
int x;
Node* parent;
public:
Node(const Node& N)
{
......
}
Node& operator =(const Node& n)
{
......
}
~Node()
{
.....
}
// other member functions
}
How do I make a copy of private field Node* parent itself? I read some
references online, some use "new" operator to allocate dynamic memory,
so what I did was
Node(const Node& p)
{
x=p.x;
Node temp=*(p.parent)
parent=new node(temp);
}
However, x value was copied, not the parent pointer.
anyone can help?
You first have to decide if you want a shallow copy or a deep copy of your
Node. For a shallow copy, a simple assignment of parent=p.parent is
sufficient. For a deep copy, your code has to be modified so that all
parents are copied, but not more. Currently, you ignore that the parent
field may be NULL. Code like
Node(const Node& p)
{
x=p.x;
if (p.parent)
parent=new Node(*(p.parent));
else
parent=0;
}
will do this by using recursion, but can be improved for this linear list
by changing this to iteration.
Since the OP doesn't say what is done in the constructor and destructor
(I see some dots there, nothing else), your suggestion might be wrong.
Also, it is not clear how the parent pointer is assigned.
Here is a better suggestion:
http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.8
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]