Open In App
Related Articles

C++ | this pointer | Question 2

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
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

Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads