this

When talking about messages, we used the terms "sender" and "target". When we're actually sending messages, we use the notion target->messageName(parameters). This does not include the sender of a message. But what if we want the system to know who the sender is?

Solution: We could add the sender as an additional parameter. Example:

class ListOfCars {
...
  void addCar(Car *c);
}

Now if a car want's to add itself to the list, it can do so. All it needs is to have an object reference to itself.

This object reference is called "this". ("self" in most other OO languages)

  • This is only valid in non-static methods (because it needs an object)

  • It will always hold the reference of (point to) the current object.

Example:

void Car::registerMe()
{
  list->addCar(this);
}

The use of "this" in setters.

Assume the following class:

class Bla
{
private:
  int attr;
public:
  void setAttr(int);
  // ...
}

//  ...


void Bla::setAttr(int attr) 
{
  this->attr = attr;
}