I have this snippet of the code
Stack& Stack:: operator=(const Stack& stack){
if(this == &stack){
return *this
}
}
here I define operator =
but I can't understand, if I receive by reference stack why it should be &
in this == &stack
and not this == stack
and why we return *
in return *this
and not this
thanks in advance for any help
Because this
is a pointer (i.e. of type Stack*
), not a reference (i.e. not of type Stack&
).
We use if(this == &stack)
just to ensure the statement
s = s;
can be handled correctly (especially when you need to delete something in the old object). The pointer comparison is true only when both are the same object. Of course, we could compare by value too
if (*this == stack)
return *this;
else {
...
}
But the ==
operation can be very slow. For example, if your stack has N items, *this == stack
will take N steps. As the assignment itself only takes N steps, this will double the effort for nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With