this Pointer in C++

C++ uses a unique keyword called “this” to represent an object that invokes a member function. ‘this’ is a pointer that points to the object for which this function was called.

This unique pointer is called and it passes to the member function automatically. The pointer ‘this’ acts as an implicit argument to all the member function.

Example:

class ABC
{
     int a ;
     public:
		void getdata()
		{
			a=123;			
		}
};

The private variable ‘a’ can be used directly inside a member function, like

a=123;

We can also use the following statement to do the same job.

this → a = 123

Example:

class stud
{
	int a;
	public:
		void set (int x)
		{
			this->a=x; 
		} 
		void show ( )
		{
			cout << a;
		}
};
void main ( )
{
	stud S1, S2;
	S1.bet (5) ;
	S2.show ( );
}

Here this pointer is used to assign a class level variable ‘a’ with the argument x.

Output:

5

Related posts