[cs13001] Questions about keyword 'this'
Mikhail Nesterenko
mikhail at cs.kent.edu
Thu Nov 13 22:52:03 EST 2014
>
> The slide says this is a pointer to the object that invokes the member
> function. What does it point to specifically?
>
It points to the object itself. That is, "this" holds the address of
the object on which the member function is invoked.
>
>
> So we're making sure the address for the calling object isn't the same
> memory location of the object passed to the function.
>
This check is done to prevent self-assignment of the kind below
from destroying the object in the overloaded assignment
object1 = object1; // self-assignment
> If it is, why do we return the data from the location this is pointing to
> instead of leaving it alone? Is it because we have to return an object of
> MyClass? Are we assigning it to itself?
>
The return value of the assignment is used to implement stackability:
object1 = object2 = object3;
Assignment is evaluated from right to left. That is, first
(object2 = object3)
expression is evaluated. Its value is then assigned to object1 And, as
defined below, the value of (object2 = object3) expression is object2,
which is assigned to object1.
Thanks,
--
Mikhail
>
> MyClass& MyClass::operator= (const MyClass& rhs){
> if (this != &rhs){ // if not same
> size=rhs.size;
> delete [] d;
> d=new int[size];
> for (int i=0; i < size; i++)
> d[i]=rhs.d[i];
> }
> return *this; // return lhs
> }
More information about the cs13001
mailing list