copy construct

E

exergy

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?
 
S

Saeed Amrollahi

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
 } [SA] };

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?

[SA] What is wrong with reference semantic (copy semantic)? consider
the following code:

class Node {
// as before
public:
Node() : x(0), parent(0) {} // for root
Node(int xx, Node* p) : x(xx), parent(p) {}
Node(const Node& N) : x(N.x), parent(N.parent) // pointer semantic
{
}
// as before
};

void use_node()
{
Node root; // root of say tree
Node n(1, &root); // one node
Node n2(2, &n); // another node
Node n3 = n2; // copy of node
}

of course we can use copy semantic ...

I hope it helps
-- Saeed Amrollahi
 
J

joseph cook

Hello, if I have a class like this:
   Node(const Node& p)
     {
       x=p.x;
OK.

       Node  temp=*(p.parent)

Calls the copy constructor recursively ?
       parent=new node(temp);
     }
However, x value was copied, not the parent pointer.
anyone can help?

If I understand what you are trying to do: Think about it, when you
try and create a unique "parent" object, it will try and create a
fresh "parent Node", and it will try to create a fresh parent node,
etc. forever.

Is this what you are trying to do? What is the depth of the tree?
Are you trying to replicate an antire tree (but just one stem,
presumably)

Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,233
Latest member
AlyssaCrai

Latest Threads

Top