Skip to content
Related Articles

Related Articles

C++ | this pointer | Question 2
  • Difficulty Level : Easy
  • Last Updated : 31 Jul, 2013
GeeksforGeeks - Summer Carnival Banner

What is the use of this pointer?
(A) When local variable’s name is same as member’s name, we can access member using this pointer.
(B) To return reference to the calling object
(C) Can be used for chained function calls on an object
(D) All of the above


Answer: (D)

Explanation: See following example for first use.

/* local variable is same as a member's name */
class Test
{
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; }
};

And following example for second and third point.

#include
using namespace std;
 
class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
  Test &setX(int a) { x = a; return *this; }
  Test &setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};
 
int main()
{
  Test obj1(5, 5);
 
  // Chained function calls.  All calls modify the same object
  // as the same object is returned by reference
  obj1.setX(10).setY(20);
 
  obj1.print();
  return 0;
}


Quiz of this Question

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :