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++

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.

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

Related Contents to follow