tags:

views:

142

answers:

4

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

+9  A: 

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.

KennyTM
Mike DeSimone
Narek
+2  A: 

stack is of type Stack&, and this is of type Stack*. You're checking if the address of stack is equal to this.

Andreas Brinck
A: 

if I receive by reference stack why it should be & in this == &stack

Because this is a pointer (or "address") and stack is a reference (not a pointer): so you need to say &stack (which means "address of stack"), so that its type matches the type of this.

why we return * in return *this and not this thanks in advance for any help

Because this is a pointer (not a reference), but the method is supposed to return a reference (not a pointer), so you need to deference it in order to turn the pointer into a reference.

ChrisW
A: 

Short answer to your two questions.

  1. As I understand you ask why we use & sign if we get reference as a function parameter(not an abject). Because reference to an abject is not address of it. You should use operator&() in order to get the address of an object.

  2. this is a pointer, but you should return reference thus you return *this

Narek