Can you explain the concept of the this pointer?

this is a pointer to an instance of its class and available to all non-static member functions.

If you have declared a class, which has a private member foo and a method bar, foo is available to bar via this->foo but not to "outsiders" via instance->foo.


The this pointer is used in a class to refer to itself. It's often handy when returning a reference to itself. Take a look at the proto-typical example using the assignment operator:

class Foo{
public:
    double bar;
    Foo& operator=(const Foo& rhs){
        bar = rhs.bar;
        return *this;
    }
};

Sometimes if things get confusing we might even say

this->bar = rhs.bar;

but it's normally considered overkill in that situation.

Next up, when we're constructing our object but a contained class needs a reference to our object to function:

class Foo{
public:
    Foo(const Bar& aBar) : mBar(aBar){}

    int bounded(){ return mBar.value < 0 ? 0 : mBar.value; }
private:

    const Bar& mBar;
};

class Bar{
public:

      Bar(int val) : mFoo(*this), value(val){}

      int getValue(){ return mFoo.bounded(); }

private:

      int value;
      Foo mFoo;
};

So this is used to pass our object to contained objects. Otherwise, without this how would be signify the class we were inside? There's no instance of the object in the class definition. It's a class, not an object.


In object-oriented programming, if you invoke a method on some object, the this pointer points at the object you invoked the method on.

For example, if you have this class

class X {
public:
  X(int ii) : i(ii) {}
  void f();
private:
  int i;
  void g() {}
};

and an object x of it, and you invoke f() on x

x.f();

then within X::f(), this points to x:

void X::f()
{
  this->g();
  std::cout << this->i; // will print the value of x.i
}

Since accessing class members referred to by this is so common, you can omit the this->:

// the same as above
void X::f()
{
  g();
  std::cout << i;
}

A pointer is a variable type which points to another location in your program's memory. Pointers only can hold addresses of memory locations.

image

For example, if we say an "int pointer" - > it holds the memory address of a int variable.

"void pointer" -> can hold any type of memory address which is not a specific data type.

The & operator gives the address of a variable (or the value of the pointer where pointed).