What is this Pointer? Give an example.

The this Pointer: When a function of a class is called by an object of that class, each variable gets an pointer which points to that calling object, meaning that this variable was called by that object or this variable is under that object. This pointer is called this pointer. To clarify consider the following lines of codes,

int pointer::example(int i, int j){
 a=i;     //line 1
 b=j;     //line 2
 if (a>b)
  return a;   //line 3
  return b;   //line 4

void main(){
 pointer ob1;
Actually each variable of line 1,2,3,4 is having pointer to the object ob1. This was not shown above. The actual form of lines 1,2,3,4 will be then as follows,

this->a=i;   //line 1
this->b=j;   //line 2
return this->a;  //line 3
return this->b;  //line 4

The this pointer is important when operators are overloaded and whenever a member function must utilize a pointer to the object that invoked it. 

Author: Tanmay Chakrabarty

Tanmay Chakrabarty is a former CSE student, currently working as a Senior Software Engineer with 5+ years of experience in the field of Web Application development in PHP+MySQL platform with strong skills in Javascript, JQuery, JQuery UI and CSS. He tries to write notes every week but fails due to heavy loads of duty.

Recommended Recommends


Contact Us