0

I was going through geeksforgeeks and found below code

#include<iostream>
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; }
};

This class seems okay for me. But the function call and its output seems bit confusing.

int main()
{
  Test obj1;
  obj1.setX(10).setY(20);
  obj1.print();
  return 0;
}

Here, if I call setX() and setY() function in single line, then the output will be: x = 10 y = 0

else, if I call those function as given below,

int main()
{
  Test obj1;
  obj1.setX(10);
  obj1.setY(20);
  obj1.print();
  return 0;
}

then the output seems x = 10 y = 20.

What is the difference between these two function call. Can someone explain using this pointer?

Thankyou in advance.

0 Answers0