C++ this Pointer

  • In C++ programming, this is a keyword.
  • this is a local object pointer in every instance member function which contains address of the current object.
  • You can not change the value in this pointer ( this can not be modified ).

WHEN TO USE THIS POINTER

  • when there is name conflict between instance member variable and local variable.
  • whenever it is required to represent current object in instance member function.

Following is the code to support above statements.


#include<iostream>

using namespace std;

class Test

{

private:

   int x;

public:

   void setX (int x)

   {

this->x = x;

   }

   void print() { cout << "x = " << x << endl; }

};

 int main()

{

   Test obj;

   int x = 20;

   obj.setX(x);

   obj.print();

   return 0;

}

THANK YOU...

Mentor - Saurabh Shukla

To view or add a comment, sign in

More articles by Ashish Kumar

  • Inline function in C++

    Before understanding inline function, we will see what is benefits & dis-advantages of defining a function. Benefits…

  • C++ Vectors

    In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow…

    2 Comments
  • Templates in C++

    Templates in C++ is defined as a blueprint or formula for creating a generic class or a function. We can create a…

    1 Comment
  • Virtual Function in C++

    A virtual function is a member function which is declared within a base class and is overridden by a derived class…

Explore content categories