Tricky things in C++ — this pointer

Privalov Vladimir
2 min readDec 16, 2021

--

When we implememt classes in C++ there is a special this pointer pointing to the current instance of the classes it is called for. Here I will show some interesting things about this pointer I have learnt.

‘this’ is const pointer

We can’t modify it. Let’s see on some toy example:

class Foo {
private:
int x;
public:
Foo(int x = 0) { this->x = x; }
void change(Foo *foo) { this = foo; }
void print() { cout << x << endl; }
};

Now let’s create some objects and try to change this pointer

Foo obj (3);
Foo *ptr;
obj.change(ptr);
obj.print();

What do you thing will be the output for this?

Correct answer is Compilation error in method change (lvalue required as left operand of assignment). This means that this is const poiner.

this pointer is available only for non-static methods

Let’s add following line to our class

static void set(int x) { this->x = x; }

and call it

obj.set(6);

This will result in compilation error “‘this’ is unavailable for static member functions”.

Notice: The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions.

distinguish local variable’s name and member’s name

Use this pointer in methods where existlocal variables with same name.

Simple example

void set(int x) { this->x = x; }

deleting object with operator delete

Operator delete can be called with pointer this only if object is created using new keyword.

Let’s create method destroy

void destroy() { delete this; }

and call it

Foo obj (3);
obj.destroy();
obj.print();

Behavior will ne undefined here.

Fourth feature:

Using for chaining calls

We can return a reference to the calling object like that

Foo &set(int x) { this->x = x; return *this; }

This can be useful if we need to chain function calls on a single object

obj.set(2).set(8);

Reference mark ‘&’ is important in method defintion. Otherwise only the first call will be executed

obj.set(2).set(8);

results in 2.

--

--

No responses yet