Class this Pointer
beginner
c++11
classes
In C++ the this
keyword is a special pointer variable that points to the object instance of a member function.
this
is implicit and does not need to be declared as an actual function parameter in order to be used and it is always made available.
You can think of this
as a hidden “self” parameter passed to every object when their member functions are called.
Using this
is optional when it is unambiguous (only one possibility) as to what you are referring to.
#include <iostream> #include <string> class Dog { public: void set_name(std::string name) { // Use `this` to make it clear we're assigning the name field // and not the name parameter this->name = std::move(name); } std::string get_name() const { // `this` is implied as "name" can only refer to one thing return name; // Identical as "return this->name;" } private: std::string name; }; int main() { Dog d; d.set_name("Doge"); std::cout << d.get_name() << "\n"; }
Doge
this
is valid for the entire duration of an object’s lifetime, meaning you can use this
in both the constructor and destructor.
#include <iostream> #include <string> class Dog { public: explicit Dog(std::string name) { // Name is a std::string* (pointer) this->name = new std::string(std::move(name)); } ~Dog() { // We must delete this->name because we called "new" delete this->name; } std::string get_name() const { return *(this->name); } private: std::string* name; }; int main() { Dog d("Doge"); std::cout << d.get_name() << "\n"; }
Doge