jscherman jscherman - 3 months ago 6
C++ Question

Assignment operator is returning an "empty" instance when it shouldn't?

I'm implementing a stack just for practicing. So, in the main, I've got something like this:

Stack stack;
stack.push(element1;
stack.push(element2);

Stack copy;
copy = stack;


So I'm overloading the assignment operator because I want to generate new elements instances also (and not just copying the pointer of each element from one to another), as follows

Stack &Stack::operator=(const Stack &toCopy) {
Stack* stack = new Stack;
if (toCopy.first == NULL) return *stack;
for (Node* actual = toCopy.first; actual != NULL; actual = actual->sig) {
stack->push(actual->elem);
}
// In this state, *stack has 2 elements as it should
return *stack;
}


Back in the main, the copy variable is not getting the changes... It's still empty as if the assignation had never happened. As if I had do just
Stack copy;
Could you explain me what is going on in here?

Answer

You're not modifying the current object (i.e. *this).

You're just creating a new object by new, then returning it. Note for copy = stack;, it's equivalent to copy.operator=(stack);, note that the returned value is not used, it's just discarded (and causes memory leak), and copy isn't changed.

You should do something like:

Stack &Stack::operator=(const Stack &toCopy) {

    // do some work to clear current elements in *this
    // ...

    // add elements from toCopy
    for (Node* actual = toCopy.first; actual != NULL; actual = actual->sig) {
        this->push(actual->elem);
    }

    // operator= is supposed to return *this in general
    return *this;
}
Comments