Tricky things in C++ — this pointer

‘this’ is const pointer

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

this pointer is available only for non-static methods

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

distinguish local variable’s name and member’s name

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

deleting object with operator delete

void destroy() { delete this; }
Foo obj (3);
obj.destroy();
obj.print();

Using for chaining calls

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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Mostly asked C Interview Questions

Mostly asked C programming interview questions, C interview questions

Custom Pagination with Spring Data and MongoDb

How I automate all my work with Python

How we reduced our infrastructure costs by 8x without sacrificing performance

Java Basics Programming for Beginners and Developers

The technical choices I make to build great Android apps. Part 1 — UI

Do Languages Die

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Privalov Vladimir

Privalov Vladimir

More from Medium

Should I make class member variables const or constexpr?

Function Objects (Functors) in C++

You say goodbye I say hellooop

How to use a dynamic library generated by Zig-lang in C++ codebase