Re: copy construct
On 8 Aug, 22:21, exergy <nicholas.entr...@gmail.com> 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?
It is debatable what taking a copy of a part of a composite structure,
a tree in this case, should actually mean.
If you copied your head would you expect to have:
(a) 1 body with 2 heads
(b) 1 body with 1 head + an unattached head
(c) 2 identical bodies
Your software solution suggests (c) because you are trying to
recursively copy the parent node whereas the more usual software
interpretation would be either (a) or, most commonly, (b).
In (b) you would just set parent = 0 in the copy.
In (a) You would just set parent = x.parent (and possibly modify the
parent if it has pointers to its children)
Interpretation (c) is not useful in software terms because it is a
clone of the entire tree.
You don't show any parent to child relationship in your example. If
there were one then it would be the usual practice to (recursively)
make copies of all the child nodes for the new node copy.
In this case you would indeed write something like AddChild( new Node
( *(this->child) ) ); i.e. you would copy the entire subtree.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]