Usage of this Pointer in C++

Written by Hamza on. Posted in C++

Thus far in this series on object oriented programming in C , we have learnt the basics of classes and objects and have touched upon the private data members and public member functions, including use of getters and setters in C . When dealing with a class, we create different objects and call a number of functions on them. Have you ever wondered: How does the compiler know on which object the function was called and to change the variables of which object inside that function? This is done using this pointer in C .

The this pointer is a special type of pointer that points to the object on which a function is called. It is a sort of hidden pointer, because it does not need to be explicitly stated when writing a program. Compiler automatically generates a this pointer to that object on which a function gets invoked. It is only accessible within a member function. Thus, it is a special type of pointer used solely for object oriented programming purposes. Each time a function is called on an object, this pointer stores the address of that object till the execution time of that function.

As this pointer is automatically pointing towards the object itself, the compiler, when compiling the program, automatically puts the key word “this->” before any data member before it executes the program, avoiding the need to explicitly use it within our code. For example, if we casino online write:

</p>
<p>class fraction</p>
<p>{</p>
<p>.  private:</p>
<p>.   int numerator;</p>
<p>.   int denominator;</p>
<p>.   public:</p>
<p>.   int <a href="http://www.ovationtv.com/scheduledata/index.html">buy viagra online</a>  useless_function (int numerator, int denominator)</p>
<p>.   {</p>
<p>.     this-&gt;numerator = numerator ;</p>
<p>.     this-&gt;denominator = denominator ;</p>
<p>.   }</p>
<p>} ;</p>
<p>.</p>
<p>int main()</p>
<p>{</p>
<p>.  fraction obj ;</p>
<p>.  obj.useless_function (2,3);</p>
<p>}</p>
<p>

 

Here is an effective use of the this pointer. We have used it to avoid ambiguity within the passed parameters, and the private data members within the class. The ones with the this pointer attached are the private data members of the object on which function was called while the ones without this pointer are the data members of the object passed.

Above is one case in which the use of the this pointer is neccesary. Another is when you use the statement:

</p>
<p>return *this;</p>
<p>

This is a special type of statement to return the object by reference. This saves memory on many occasions, which hopefully I will cover in the next articles.

This was all you needed to know about the this pointer. Let us move on now to something a bit more interesting. Stay tuned for the next article in the series!

Tags: , , , ,