CPP this Pointer

The this Pointer.

  • Every class member function has a hidden pointer: the this pointer, which points to "this" individual object.
  • In some cases the this pointer can be a powerful tool.
    Here is an Example
    #include <iostream>
    using namespace std;
    class Rectangle {
      public:
        void setLength(int length)
          { this->length = length; } // this object length= parameter length
        int getLength() const
          { return length; }
    
        void setWidth(int width)
          { this->width = width; } // this object width= parameter width
        int getWidth() const
          { return width; }
    
      private:
        int length;
        int width;
    };
    int main() {
       Rectangle * pRectangle = new Rectangle;
       pRectangle->setLength(34);
       cout << "The Rectangle length is " << pRectangle->getLength() << endl;  
       delete pRectangle;
       pRectangle=0; // Good rule but not necessary at this place
       return 0;
    }
    When we run this application the result could be:
    The Rectangle length is 34

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.