this pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Geevi
    New Member
    • Jan 2007
    • 13

    this pointer

    Hi all,

    can u explain about this pointer with example...

    how to use and where to use?

    how can we return objects with this pointer?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    this is a keyword in C++ that evaluates to a pointer to the current object.

    It is only valid inside non-static member functions of a class (or struct).

    These functions can return this (a pointer to the object) or *this (the object or a reference to the object depending on how the function is declared).

    Comment

    • macklin01
      New Member
      • Aug 2005
      • 145

      #3
      I've only needed the this pointer on rare occasions. Here's an example (but shortened):

      Suppose you have a Contour class that contains a linked list of data points and pointers to previous and next contours. Something like this:
      Code:
      class Contour{
      private:
       DataPoint* pFirstDataPoint;
       bool IsClosed;
       Contour* pPreviousContour;
       Contour* pNextContour;
      public:
       Contour();
       ~Contour();
       bool CleanContour( void );
       // etc
      };
      Suppose that you want the CleanContour() function to remove all contours prior to and after the object, but not the object. Then you might do something like this:

      Code:
      bool Contour::CleanContour( void )
      {
       Contour* pCurrentContour = this;
       // find the "first" contour
       while( pCurrentContour->pPreviousContour )
       { pCurrentContour = pCurrentContour->pPreviousContour; }
      
       // delete all contours but this one
      
       while( pCurrentContour )
       {
        Contour* pTemp = pCurrentContour->pNextContour;
        if( pCurrentContour != this )
        { delete pCurrentContour; }
        pCurrentContour = pTemp;
       }
       pPreviousContour = NULL;
       pNextContour = NULL;
       return true;
      }
      So, what's going on here is that we're first going as far back along the linked list as we can, then progressing forward and deleting everything, taking care to not delete our current object.

      Yes, this could have been done differently without this "this" pointer. (Delete backward, then delete forward.) However, there are cases where the "this" keyword is helpful for identifying when you've reached the current object, and this illustrates how to use it.

      Another potential use: print out "this" as part of an error message to identify the memory address of an object that causes an error.

      I hope this is somewhat helpful. -- Paul

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        You use this a bit when overloading operators because you are often expected to return a reference to the object just operated on.

        Comment

        • ramudukamudu
          New Member
          • Jan 2007
          • 16

          #5
          Originally posted by Geevi
          Hi all,

          can u explain about this pointer with example...

          how to use and where to use?

          how can we return objects with this pointer?
          Hi, When objects are created, memory will be allocated only for data members. member funcitons will be stored seperately(this avoids unnecessary duplication). If you r going to invoke a member funciton, reference of the object is passed to the member function through a pointer called "this". For a class of type "Circle", "this" will be "Circle* const this". So "this" pointer is automatically created once you invoke the member funciton.

          Uses:
          1> If the arguments of the constructors clash with the member functions:
          class Circle
          {
          float radius;
          Circle(float radius)
          {
          this.radius = radius;
          }
          ............... ...
          2> During operator overloading if you want to return the result


          Complex & Complex::operat or +=(Complex temp) {
          re += temp . re ;
          im += temp .im ;
          return * this ;
          }

          Comment

          • nandeshwar
            New Member
            • Jan 2007
            • 4

            #6
            Originally posted by Geevi
            Hi all,

            can u explain about this pointer with example...

            how to use and where to use?

            how can we return objects with this pointer?

            I am writing two programs that may help you understanding usage of this pointer,
            Code:
            #include<iostream.h>
            #include<conio.h>
            #include<string.h>
            class Test
            {
               private:
                     int id;
                     char name[30];
               public:
                   Test(int id,char name[30])
                    {                                // id is local variabe as well as instance variable
                       this->id=id;                //  "this->id" means object id or instance id
                       strcpy(this->name,name);  // "id" means local id in this function
                   }                                          
                void display()
                {
                   cout<<id<<endl;
                   cout<<name<<endl;
               }
            };
            
            void main()
            {
                 Test t(1,"Nandeshwar");
                  t.display();
                  getch();
            }
            
            
            Another Program 
            
            #include<iostram.h>
            #include<conio.h>
            
            class Test
            {
                 private:
                    int id,age;
                 public:
                       Test()
                        {
                        }
                      Test(int id,int age)
                       {
                          this->id=id;
                          this->age=age;
                       }
                        void display()
                        {
                            cout<<"Id: "<<id<<"is senior person of age"<<age<<endl;
                         }
                      Test operator>(Test t2);
            };
            Test Test::operator>(Test t2)
            {
                 if(age>t2.age)
                        return *this; //here returning first object
                 else
                     return t2;     //here we are returning 2nd object i.e. t2
            }
            
            void main()
            {
               clrscr();
               Test t1(1,29);
               Test t2(2,25);
               Test t3;
                
              t3=t1>t2;
              t3.display();
              getch();
            }
            Last edited by horace1; Jan 14 '07, 04:16 PM. Reason: added code tags

            Comment

            • ogedezvoltare
              New Member
              • Mar 2007
              • 18

              #7
              Originally posted by ramudukamudu
              Uses:
              1> If the arguments of the constructors clash with the member functions:

              }
              i think here is a little mistake, the correct expresion will be
              If the arguments of the constructors clash with the member variables:

              Comment

              Working...