Code With Nil's

This Pointer

 

  • Every object in C++ has access to its own address through an important pointer called this pointer.
  • The this pointer is an implicit parameter to all member functions.
  • Therefore, inside a member function, this may be used to refer to the invoking object.
  • Friend functions do not have a this pointer, because friends are not members of a class.
  • Only member functions have a this pointer.
  • The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions.
  • this’ pointer is a constant pointer that holds the memory address of the current object.
  • this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
  • this pointer is nonmodifiable, assignments to this are not allowed.

-----------------------------------------------------------------------------------

Class demo
{
public :

int mn;

void fun( int mn )
{
   month = mn;              // These three statements
   this -> month = mn;       // are equivalent
   (*this).month = mn;
}

};

when we call this function like
demo obj;
obj.fun(20);

then it is converted as

fun(&obj, 20);

syntax of the function fun is

void fun(demo * const this, int mn);

In this case first parameter is considered as a this pointer.

-----------------------------------------------------------------------------------

Following are the situations where ‘this’ pointer is used:

-----------------------------------------------------------------------------------
  • When local variable’s name is same as member’s name
class demo
{
private:
   int x;
public:
   void setX (int x)
   {
       // The 'this' pointer is used to retrieve the object's x
       // hidden by the local variable 'x'
       this->x = x;
   }
   void print() { cout << "x = " << x << endl; }
};

-----------------------------------------------------------------------------------
  • To return reference to the calling object

class demo
{
public:
int a;
demo()
{
a = 10;
printf("demo constructor");
}

demo& fun ()
{
//
// Some processing on caller object and return modified object
//
this->a = 20;
return *this;
}

};

-----------------------------------------------------------------------------------

No comments:

Post a Comment

Pages

Copyright © 2018 - Created by Nilesh Bachhav