C++ this pointer – A Complete Guide to get started!

Filed Under: C++
C This Pointer

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!

this->variable=value; //syntax of referring to the instance variable of the class'

this* // syntax for referring to the current object of the class/function

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

#include <iostream>
using namespace std;
class Point {
private:
  int val;
 
public:
  void set(int val){
    this->val = val;
  }
  void show(){
    cout<<"Value of variable: "<<val<<endl;
  }
};
int main(){
  Point ob;
  ob.set(500);
  ob.show();
  return 0;
}

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:

Value of variable: 500

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

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages