The keyword ‘this’ is a special type of pointer in c++. Here we will learn some facts of this pointer in c++. this pointer refers to the current object. it means ‘this’ pointer contains the address of the object using which the member function is being called. Let us look at below code.

Some facts of this pointer in c and c++

#include<iostream>
using namespace std;

class Add
{
  int a;
  int b;
  int s;
public:
  Add ():a (0), b (0), s (0){ }
  void add_method (int a, int b)
  {
    s = a + b;
  }
  void print ()
  {
    cout << s << endl;
  }
};

int main ()
{
  Add add_obj;
  add_obj.add_method (5, 2);
  add_obj.print ();
  return 0;
}

The function add_method is called at line 24 by using object add_obj. The add_method(int a, int b) has two arguments but when we call add_obj.add_method (5, 2), compiler converts from add_method( int a, int b) to add_method(&add_obj,int a, int b). i.e address of object is being passed in a function.

  1. ‘this’ pointer can be used only in the non static member function of the class.
  2. ‘this’ pointer is a const pointer. so it is illegal to modify this.
  3. If you declare a local variable in a method with the same name as an existing member, you will have to use this->variable to access the class member instead of the local variable.
#include <iostream>
using namespace std;
class sample
{
    public:
        int var;
        void func() {
            var = 10;
            int var = 20;
            cout << var << endl;
            //to access data member var 
            // we need to use this
            cout << this->var << endl;
        }
};

int main()
{
    sample obj;
    obj.func();
}

Some facts of this pointer in c++ where this is necessary



Related Contents to follow