What Is The Use of ‘this Pointer’?

[toc]

1. Introduction

We know that a class can have member functions and member variables. How do we extract the calling object from inside the called member function? The answer is, this pointer. It actually refers the object that called the member function. The pointer is valid when the call is transferred to the member function. Moreover, it becomes empty when call returns.

In many circumstances, we may need to return the current object to the caller of the member function. Now, we will explore this with a suitable example.

2. The ‘this Pointer’ Example

The complete code which uses the ‘this pointer’ is shown below:

3. Code Explanation

The constructor initializes the data members x and y from the parameters passed to the constructor.

Next, we write a function called Point2d* Increment() and the intent of this function is to increment the data members by 1 and return the current object. How do we return the current object? This is where the usage of the keyword this comes into the picture. In the below code you can see the usage of the ‘this pointer’ with the return statement.

The Point2d Decrement()  function implementation is similar to the previous function. But this time, we return the object itself instead of returning a pointer to the current object. Below is the function which decreases the Point2d  value by one.

The Print  function just prints the values in the coordinate x, y. This function is shown below:

In the main, first, we created two points pt1 , pt2 . Then, we increment pt1 and store the return address in a pointer called inc_point . Next, we decrement the pt2 and copy the return value to the variable dec_point . The code is shown below:

The below picture illustrates how the objects are referred from the member functions:

This Pointer Example

This Pointer Example

The below screenshot shows the program output:

This Pointer Example: Output

This Pointer Example: Output



Categories: C++

Tags: ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: