C++ recap: “this” pointer
How classes work under the hood:
#include <iostream> class Something { private: int id; public: /* Something::Something(*const this, int _id) */ Something(int _id) { setId(_id); } /* void setId(Something *const this, int _id) */ void setId(int _id) { id = _id; } /* int getId(Something *const this) */ int getId() { return id; } }; int main() { Something sth(99); /* sth.setId(&sth, 44) */ sth.setId(44); /* sth.getId(&sth) */ std::cout << sth.getId() << std::endl; }
Using
#include <iostream> class Calc { private: int value; public: Calc() { value = 0; } Calc &add (int v) { value += v; return *this; } Calc &sub (int v) { value -= v; return *this; } Calc &mul (int v) { value *= v; return *this; } int getValue() { return value; } }; int main() { int stackVariable; Calc c; c.add(10).sub(5).mul(5); std::cout << c.getValue() << std::endl; } /* Note that I need to return the address of the current object (&*this) and NOT the address of the this pointer to the object! (&this) (gdb) Calc::add (this=0x7fff5fbffb00, v=10) at 4.this.cpp:11 11 Calc &add (int v) { value += v; return *this; } (gdb) p this $1 = (Calc * const) 0x7fff5fbffb00 (gdb) p &this $2 = (Calc * const *) 0x7fff5fbffad8 (gdb) p &*this $3 = (Calc * const) 0x7fff5fbffb00 */