'this' pointer in C++





  • The this pointer is an implicit parameter to all member functions.

  • this pointer represents the current or invoking object of class.

  • this pointer is not accessible in static member function.

  • Friend functions do not have this pointer, because friends are not members of class.

  • Only member functions/non-static function have this pointer.

Following are the situations where ‘this’ pointer is used:

  1. When local variable’s name is same as member’s name
    Example:
    #include<iostream>
    using namespace std;
    /* local variable is same as 
    a member's name */
    class Test
    {
    private:
     int x;
    public:
     void setX (int x)
      {
    /* The 'this' pointer is used to 
      retrieve the object's x hidden
       by the local variable 'x'
     */
        this->x = x;
      }
     void show()
      {
       cout<<"x = " << x << endl; 
      }
    };
     
    int main()
    {
       Test obj;
       int x = 20;
       obj.setX(x);
       obj.show();
       return 0;
    }                    
    OUTPUT:
    x = 20
  2. To return reference to the calling object.
    /* Reference to the calling
     object can be returned */
    Test& Test::func ()
    {
       // Some processing
       return *this;
    }                  

Next topic is File handling





 



Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved