+ 2
What is this pointer
5 Answers
+ 2
Instead of using variable name to access memory location we can access those memory location using the address of that location a pointer is a special variable to store that memory address.
+ 2
Where as This pointer always holds the the current objects under scope
+ 1
The this pointer is used to point to the current object in use.
class myClass
{
public:
void setX(int x)
{
this->x = x;
}
private:
int x;
};
int main()
{
myClass obj;
obj.setX(5);
}
The most basic way of demonstrating the this pointer. In the setX function, for the scope that we are in, the variable 'x' is being used from the function parameters, NOT from the class.
this->x specifies that we want to use the variable 'x' from the class, or from the current object that we are using.
Of course, if the two variables had different names, this would be unnecessary :) but in my opinion it makes code look a lot cleaner and easier to read, without the use of another silly variable for the function, such as "int inputX".
+ 1
0
This -> can also help you to access an object's variable inside the class instead of the global one.
https://code.sololearn.com/clhLD96GS0AP/?ref=app