The Keyword this
Go Up to Classes Index The keyword this:
- Is passed as a hidden argument in all calls to nonstatic member functions.
- Is a local variable available in the body of any nonstatic member function.
- Does not need to be declared and is rarely referred to explicitly in a function definition.
- Is used implicitly within the function for member references.
Nonstatic member functions operate on the class type object with which they are called. For example, if x is an object of class X and f() is a member function of X, the function call x.f()
operates on x.
Similarly, if xptr is a pointer to an X object, the function call xptr->f()
operates on *xptr. But how does f know which instance of X it is operating on? C++ provides f with a pointer to x called this.
If x.f(y) is called, for example, where y is a member of X, this is set to &x and y is set to this->y
, which is equivalent to x.y.