Tricky things in C++ — this 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();
static void set(int x) { this->x = x; }
obj.set(6);
void set(int x) { this->x = x; }
void destroy() { delete this; }
Foo obj (3);
obj.destroy();
obj.print();
Foo &set(int x) { this->x = x; return *this; }
obj.set(2).set(8);
obj.set(2).set(8);

--

--

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