0

I am creating a stack with the following Attributes and I am trying to create a copy-constructor and an assignment-operator but I can't since the new object and the old one point to the same memory. Please assist.

class Node
{
public:
    Node(const T& data, Node* n = 0)
    {
        element = data;
        next = n;
    }

    T element;
    Node* next;
};

/* The top of the stack */
Node* top;
David G
  • 94,763
  • 41
  • 167
  • 253

2 Answers2

0

For copy constructor do it like

Node(const Node& data)
{
    element = data.element;
    next=new Node();
    *next = *data.next;
}
Hamza
  • 1,593
  • 2
  • 19
  • 31
0

Assignment Operator :

Node& operator=(const Node& data) {
    if (this != &other) { // to avoid self-assignment
        element = data.element;

        // allocate new memory
        Node* tmp = new Node();
        std::memcpy(tmp, data.next, sizeof(Node));

        // deallocate old memory
        delete next;

        // assign new memory to object
        next = new Node();
        std::memcpy(next, tmp, sizeof(Node));
    }
    return *this; 
}

Exception safety is taken into consideration.

Tyson90
  • 106
  • 8