Use of this pointer

Explain the use of this pointer.

- The this keyword is used to represent an object that invokes the member function. It points to the object for which this function was called. It is automatically passed to a member function when it is called.
- For example when you call A.func(), this will be set to the address of A.

Explain the use of this pointer.

- When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object (ie the object on which the function is invoked). This pointer is known as 'this' pointer. It is internally created at the time of function call.
- The this pointer is very important when operators are overloaded.
- Example : Consider a class with int and float data members and overloaded Pre-increment operator ++.
class MyClass
{
   int i;
   float f;
   public:
       MyClass ()
       {
          i = 0;
          f = 0.0;
       }
       MyClass (int x, float y)
       {
          i = x; f = y;
       }
       MyClass operator ++()
       {
          i = i + 1;
          f = f + 1.0;
          return *this; //this pointer which points to the caller object
       }
       MyClass show()
       {
          cout<<”The elements are:\n” cout<i<<”\n<f;   //accessing data members using this
       }
};

int main()
{
   MyClass a;
   ++a;   //The overloaded operator function ++()will return a’s this pointer
   a.show();
   retun 0;
}
The output would be :
The elements are:
1
1.0

When do you use this pointer?

- 'this pointer' is used as a pointer to the class object instance by the member function. The address of the class instance is passed as an implicit parameter to the member functions.
Explain what happens when a pointer is deleted twice - C++
Explain what happens when a pointer is deleted twice - If you delete a pointer and set it to NULL, it it possibly cannot have an adverse effect....
What is a smart pointer?
What is a smart pointer? - Smart pointers are objects which store pointers to dynamically allocated (heap) objects..
Difference between an inspector and a mutator - C++
Difference between an inspector and a mutator - The get() functions are usually refered to as inspectors as that just retrieve the data values from the source....
Post your comment