0

My problem is, that I have a class which has as an object of itself. When I try to write the assignment or copy method I end in a kind of "classception"

the shortened class:

class Node
{
public:
    Node(QString name, Node *parent = 0);
    ~Node(void);

    // copy
    Node(const Node &srcNode);
    // assignment
    Node& operator=(const Node &srcNode);

    private:

    QString name;
    QList<Node*> children;
    Node *parent;
};

and the method (just one because its almost the same)

// Copy
Node::Node(const Node &srcNode)
{
    name = srcNode.name;

    for(int i = 0; i < srcNode.children.size(); i++)
    {
        children.replace(i, srcNode.children.at(i));
    }

    // how is it done?
    parent = srcNode.parent;
}

My problem is at the last line of the method. As you can see the parent is also an object of the type Node, so I would end up in an endless loop.

How do i deep copy this class correctly?

Hope that someone can give me a hint :)

Regards

David Saxon
  • 1,406
  • 1
  • 12
  • 23
Michael Brenndoerfer
  • 3,483
  • 2
  • 39
  • 50
  • 2
    How do you know you end up in an endless loop? They're pointers, not the actual objects. – David G Jan 02 '13 at 23:32
  • Have you tried to use it? It shouldn't be problem with a pointer. However that is not a "deep copy" you only changing the pointer. – Matzi Jan 02 '13 at 23:33
  • 1
    Actually, `parent` is of type `Node*`, not Node. That assignment should not trigger a recursive assignement/copy because you are not copying a Node object, but a pointer to a Node. – Timo Geusch Jan 02 '13 at 23:34
  • I've tried it but it's bounded into a qt app. When it didn't worked i thought it would be because of a mistake here. but seems not to be the case :/ – Michael Brenndoerfer Jan 02 '13 at 23:56

1 Answers1

0

There is no infinite loop going on here because both objects are of type Node*, so the copy-constructor does not get invoked in that expression. Actions between pointers of a certain type are completely separate from actions between objects of those actual types.

David G
  • 94,763
  • 41
  • 167
  • 253
  • Ah ok - and is a deep copy necessary for the QList ? Also just children = srcNode.children; ? – Michael Brenndoerfer Jan 02 '13 at 23:51
  • 1
    @David: I wouldn't expect `children = srcNode.children;` to do a **deep** copy -- it seems like that would produce a `Node` that shares children with another `Node`. – Nate Kohl Jan 03 '13 at 00:01
  • 1
    @Michael Kohl is right: `children = srcNode.children` won't do a deep copy, so it's up to do so. – David G Jan 03 '13 at 00:05