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
thisis a pointer (i.e. of typeStack*), not a reference (i.e. not of typeStack&).We use
if(this == &stack)just to ensure the statementcan 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
But the
==operation can be very slow. For example, if your stack has N items,*this == stackwill take N steps. As the assignment itself only takes N steps, this will double the effort for nothing.