Programming Tutorials

this Pointer in C++

By: Jagan in C++ Tutorials on 2007-09-14  

Every class member function has a hidden parameter: the this pointer. this points to the individual object. Therefore, in each call to GetAge() or SetAge(), the this pointer for the object is included as a hidden parameter.

It is possible to use the this pointer explicitly, as program below illustrates.

Using the this pointer.


1:      // 
2:      // Using the this pointer
3:
4:      #include <iostream.h>
5:
6:      class Rectangle
7:      {
8:      public:
9:           Rectangle();
10:           ~Rectangle();
11:           void SetLength(int length) { this->itsLength = length; }
12:           int GetLength() const { return this->itsLength; }
13:
14:           void SetWidth(int width) { itsWidth = width; }
15:           int GetWidth() const { return itsWidth; }
16:
17:      private:
18:           int itsLength;
19:           int itsWidth;
20:      };
21:
22:      Rectangle::Rectangle()
23:      {
24:          itsWidth = 5;
25:          itsLength = 10;
26:      }
27:      Rectangle::~Rectangle()
28:      {}
29:
30:      int main()
31:      {
32:           Rectangle theRect;
33:           cout << "theRect is " << theRect.GetLength() << " feet long.\n";
34:           cout << "theRect is " << theRect.GetWidth() << " feet wide.\n";
35:           theRect.SetLength(20);
36:           theRect.SetWidth(10);
37:           cout << "theRect is " << theRect.GetLength()<< " feet long.\n";
38:           cout << "theRect is " << theRect.GetWidth()<< " feet wide.\n";
39:      return 0;
40: }

Output: theRect is 10 feet long.
theRect is 5 feet wide.
theRect is 20 feet long.
theRect is 10 feet wide.

Analysis: The SetLength() and GetLength() accessor functions explicitly use the this pointer to access the member variables of the Rectangle object. The SetWidth and GetWidth accessors do not. There is no difference in their behavior, although the syntax is easier to understand.
If that were all there was to the this pointer, there would be little point in bothering you with it. The this pointer, however, is a pointer; it stores the memory address of an object. As such, it can be a powerful tool.

You don't have to worry about creating or deleting the this pointer. The compiler takes care of that.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)