6.4 POINTER “this

Sometimes we need to refer to an object inside the method. Methods are called with help of dot operator or arrow operator depending on the case. Consider the example of class Date. A method set_date() may be invoked as d1.set_date() or dptr-> set_date(). You will agree with me that code of the method has no way to know that it has been invoked for object d1. To solve this problem, C++ provides pointer “this”. Inside the code of the method, pointer “this” refers to object with which it is invoked. For example, d1 in the above case.

There are many uses of this facility. Assume that a function returns a pointer to object. Imagine a case where this function has to return the pointer pointing to the object with which the method ...

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.