Coders Packet

Concept of 'this' pointer in C++

By Akansh Upadhyay

In this guide we will learn the concept of 'this' pointer, it's use and how to implement in the C++ program.

What is this pointer?

When we create an object, we can access its address through an important pointer called this pointer. The 'this' pointer is used as an implicit parameter to all the member functions.

We pass the 'this' pointer as a hidden argument to all nonstatic member function calls which is available as a local variable within the body of functions.

Example:

1. Suppose there is an object xyz calling one of the member functions say sample().

2. Then the function sample() will hold the address of object xyz through this pointer.

3. The this pointer acts as an implicit argument to all member functions here.

Use of this pointer

There are many ways to use this pointer:

1. When the class variable name and parameter/argument name are same

When the variable declared inside the class is same as the variable used in the method to accept the parameter/argument, we use this pointer to distinguish between the two when assigning values.

Example

class abc{
  int p,q;
  public:
    abc(int p,int q)
    {
      this->p=p;
      //Here the variable used with this is class variable
    }
};

2. Return Object

We use this pointer to return the reference to the object it points to.

Example

class abc{
  int p,q;
  public:
    abc& functionName()
    {
   		//Statements
   		return *this; //returns the reference to the object
   		}
};

Program

#include
using namespace std;
class student{
  private:
    int rollno,marks;
  public:
    student(int rollno=2)
    {
      this->rollno=rollno;
    }
    student& getstudent(int n)
    {
      cout<<"\nThe value of private variable declared in class= "<<rollno; //parameter assigned to class variable in above method
      cout<<"\nThe address of object= "<<this;
      marks=n;
      return *this; //returns current object
    }
    void showstudent()
    {
      cout<<"\nThe address of object= "<<this;
      cout<<"\nThe marks= "<<marks;
    }
    
};
int main()
{
  student st;
  st.getstudent(98).showstudent(); //No need to call showstudent() explicitly,we call it on the returned object
  return 0;
}

Output:

this pointer

 

 

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Akansh Upadhyay (akansh)

Download packets of source code on Coders Packet