Cpp Tutorial: Cpp this pointer in C++

In this chapter we shall learn about below topics:
1. What is this pointer in C++?
2. Where is “this” pointer is accessible?
Usage of “this” pointer:
1. Usage 1
2. Usage 2
3. Usage 3

What is this pointer in C++?

“this” pointer holds the address of the current object that is being called. It is passed as an internal argument to the function.

Where is “this” pointer is accessible?

It is accessible inside the non-static member functions of the class. As static member functions can be called without an object, “this” pointer will not be available for them.
Friend functions will not have this pointer, because friend function is not a member function of that class.
How does the compiler sends “this” pointer to a function.
Example:
myObj.myFun();
This will be converted into
myFun(&myObj);

Usage of “this” pointer:

Usage 1:

When the data member and local variable names are same. In this situation we use this pointer to distinguish between the variables.
#include <iostream>
using namespace std;

class MyClass
{
  
  int num;
  
  public:
  
  void display(int num)
  {
      this->num =  num;
      
      cout<<"The num value is "<< this->num<<endl;
  }
    
};

int main(void)
{
    MyClass myObj;
    myObj.display(10);
    
    return 0;
}

Usage 2:

When you want to return a reference to the calling object.

MyClass& MyClass::display () 
{ 
  
   return *this; 
}

This will be useful in method chaining, we shall discuss that below.

Usage 3:

Method Chaining

Suppose for example, you have a function “add” and you need to set the value “a” and value “b”.
Normally you would do like below:

myObj.setA(10);
myObj.setB(20);
myObj.add();
But with method chaining we can do:
myObj.setA(10).setB(20).add();

This is possible because we are returning the object reference.

Full Example:

#include <iostream>
using namespace std;

class MyClass
{
  
  int a;
  int b;
  
  public:
  
    MyClass& setA (int num) 
    { 
        a = num;
        return *this; 
    }  
    
    MyClass& setB (int num) 
    { 
        b = num;
        return *this; 
    }      
    
    void add()
    {
        cout<<" Sum is "<< (a + b)<<endl;
          
    }
    
};

int main(void)
{
    MyClass myObj;
    myObj.setA(10).setB(20).add();
    
    return 0;
}

Output:

Sum is 30
Write a Comment

Leave a Comment

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