What is purpose of this
keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this
to call peer methods inside a class?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Do the Java Integer and Double objects have unnece
- Why does const allow implicit conversion of refere
- thread_local variables initialization
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Some points to be kept in mind
This pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.
This pointer is not counted for calculating the size of the object.
This pointers are not accessible for static member functions.
This pointers are not modifiable
Look at the following example to understand how to use the 'this' pointer explained in this C++ Tutorial.
Thus, a member function can gain the access of data member by either using this pointer or not. Also read this to understand some other basic things about this pointer
The expression
*this
is commonly used to return the current object from a member function:The
this
pointer is also used to guard against self-reference:The
this
pointer inside a class is a reference to itself. It's needed for example in this case:(while this would have been better done with an initialization list, this serves for demonstration)
In this case you have 2 variables with the same name
Using
this->number
, you let the compiler know you're assigning to the class-private variable.For clarity, or to resolve ambiguity when a local variable or parameter has the same name as a member variable.
Two main uses:
To pass
*this
orthis
as a parameter to other, non-class methods.Consider the case when a parameter has the same name as a class member: