C++ this pointer - A Complete Guide to get started! With Examples

Hey folks! Today we will be having a look at an interesting topic in the world of programming โ€” C++ this pointer.

So, let us begin!


Working of C++ this pointer

C++ deals with objects and classes, being a programming language. C++ this pointer actually points at the current object of the class i.e. it stores and represents the address of the current object of the particular class.

The this pointer serves as an implicit parameter to all the non-static functions of the class. So, we can consider this pointer as a pointer in a way to invoke the current object when being used inside the member functions.

Moreover, this pointer also enables us to refer to the instance variable of the current class being called.

Note: Since, the static functions do not make use of objects to call their variables, thus, the static functions do not contain this pointer as an implicit parameter.

Let us now focus on the structure of this pointer in the upcoming section!


Syntax of the C++ this pointer

Have a look at the below syntax!

Summarizing the above section, the following are the basic functionality served by this(->) pointer:

  • Point to the current object in the class/function.
  • Refer to the instance variables of the current class in process/use.

Example of this pointer

In the below example, we have created a class โ€˜Pointโ€™ wherein we have defined a private data member as โ€˜valโ€™. Further, we have created two functions โ€“ โ€˜showโ€™, โ€˜setโ€™ which consists of an instance variable โ€˜valโ€™.

So, as we can clearly understand, the above program contains a data member and a local variable having the same name โ€“ โ€˜valโ€™. In this case, this pointer enables us to assign a value to the classโ€™s instance variable through the local data member.

Output:


Conclusion

By this, we have reached to the end of this topic. Feel free to comment below, in case you come across any question.

Till then, Stay tuned @ C++ programming with JournalDev and Keep Learning!! ๐Ÿ™‚


References

By admin

Leave a Reply

%d bloggers like this: