GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

this pointer

#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; cout<<"hi:"<<endl;return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};

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

o/p:-
hi:
x = 10 y = 0

please explain the logic??

asked Oct 22, 2016 by bambhole

1 Answer

you are not calling the methods properly.Test class has two different methods setX and setY.These can be referenced only one at a time using an object.

the correct way would be:

obj1.setX(10);

obj1.setY(20);

the dot(.) operator is accesses just the next arguement.(here setX(10)),so the compiler goes to setX and set the value of x to 10. and the value of y remains unchanged.

 

answered Oct 22, 2016 by rksh0786
...