C++ this pointer
In C++,thisThe this pointer is a special pointer that points to the instance of the current object.
In C++, every object can, throughthisThe this pointer is used to access its own address.
thisa hidden pointer, which can be used in a class's member functions, and it can be used to point to the calling object.
When a member function of an object is called, the compiler implicitly passes the address of that object as the this pointer.
Friend functions do not havethispointer, because a friend is not a member of the class; only member functions have it.thispointer.
The following example helps to better understand the concept of the this pointer:
Example
The output result of the above code execution is:
Value: 42
Example Analysis:
-
In the above example, we defined a class named MyClass, which has a private member variable value.
-
The setValue() function in the class is used to set the value of value, while the printValue() function is used to print the value of value.
-
In the setValue() function, we use the this pointer to refer to the current object's member variable value, and assign the passed-in value to it. This clearly tells the compiler that we want to access the current object's member variable, rather than a function parameter or local variable.
In the printValue() function, we likewise use the this pointer to refer to the current object's member variable value and print it out.
-
In the main() function, we create an object obj of MyClass, then use the setValue() function to set value to 42, and print it out via the printValue() function.
-
By using the this pointer, we can access the current object's member variables in member functions even if they have the same names as function parameters or local variables. This avoids naming conflicts and ensures we access the correct variable.
More Examples
The following example is used to compare the volumes of cuboids:
Example
When the above code is compiled and executed, it produces the following results:
调用构造函数。 调用构造函数。 Box2 的体积大于或等于 Box1other extensions