The "this" pointer is a compiler-generated pointer during a function call that points to the object upon which that function gets called.
Multiple objects of the same class have identical data members in them. Whenever a function gets called on an object, only the data members of that particular object are changed. The compiler knows which object's data members to access and modify by use of a special pointer, known as the this
pointer, which stores the object's address in memory.
Whenever a function gets called on an object, the compiler automatically creates the this
pointer and sends it to the function. Because of this, there is no need to explicitly declare or pass this
to the function.
this
is a keyword in the C++ language and is used in conjunction with the arrow member operator ->
when used within a class to access its data members and functions.
void myClass::myFunction()
{
this->myVariable = 10;
}
Which is equivalent to:
void myClass::myFunction()
{
myVariable = 10;
}
Sometimes, the object itself is returned using the this
pointer:
void myClass::myFunction()
{
...
return (*this);
}