The this Pointer in C++

The this pointer points to the calling object itself.

Sometimes you need to reference a class’s hidden data field in a function. For example, a data field name is often used as the parameter name in a set function for the data field. In this case, you need to reference the hidden data field name in the function in order to set a new value to it. A hidden data field can be accessed by using the this keyword, which is a special built-in pointer that references the calling object. You can rewrite the Ci rcl e class defined in CircleWithPrivateDataFields.h in Listing 9.9 using the this pointer, as shown in Listing 11.10.

Listing 11.10   CircleWithThisPointer.cpp

1 #include “CircleWithPrivateDataFields.h” // Defined in Listing 9.9
2
3
// Construct a default circle object
4 Circle::Circle()
5 {
6    radius =
1;
7 }
8
9
// Construct a circle object
10 Circle::Circle(double radius)
11 {
12   
this->radius = radius; // or (*this).radius = radius;
13 }
14
15
// Return the area of this circle
16 double Circle::getArea()
17 {
18   
return radius * radius * 3.14159;
19 }
20
21
// Return the radius of this circle
22 double Circle::getRadius()
23 {
24   
return radius;
25 }
26
27
// Set a new radius
28 void Circle::setRadius(double radius)
29 {
30   
this->radius = (radius >= 0) ? radius : 0;
31 }

The parameter name radius in the constructor (line 10) is a local variable. To reference the data field radius in the object, you have to use this->radius (line 12). The parameter name radius in the setRadius function (line 28) is a local variable. To reference the data field radius in the object, you have to use this->radius (line 30).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *