Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

What Is The Use of ‘this Pointer’?

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


comes into the picture. In the below code you can see the usage of the ‘this pointer’ with the return statement.


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


  value by one.



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

In the main, first, we created two points




. Then, we increment


and store the return address in a pointer called


. Next, we decrement the


and copy the return value to the variable


 . 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.