Lesson 142 +10 XP

The this Pointer

The this Pointer

Inside is "member function", the this pointer points to the exact object the call is running for. Call a.speed() and this points at a; call b.speed() and it points at b.

Disambiguating names

When a parameter shares a name with a member, this-> picks the member:

class Car {
public:
  string brand;
  void rename(string brand) {   // name collides
    this->brand = brand;          // member = this->brand, param = brand
  }
};

this->brand clearly means the member, and the right-hand brand is the parameter.

chaining with return *this

Methods can hand back the object itself so calls can be chained:

class Counter {
  int value = 0;
public:
  Counter &up() {
    ++value;
    return *this;        // return the current object
  }
};

Counter c;
c.up().up().up();        // three increments, one after the other

Each call returns the same object, so the next call lands on it.

TL;DR

  • this points to the object for the current call.
  • this->member disambiguates a member from a same-named parameter.
  • return *this; returns the current object for chaining.
  • Static functions have no this pointer.