-1

I was learning about this pointer in C++ that it contains address of class object. But I have a problem understanding my code.

#include<bits/stdc++.h>
using namespace std;
class Point
{
    private:
        int x,y;
    public:
        Point(int x, int y)
        {
            this->x = x;
            this->y = y;
        }
        
        Point setX(int x)
        {
            this->x = x;
            return *this;
        }
        Point setY(int y)
        {
            this->y = y;
            return *this;
        }
        int getX()
        {
            return x;
        }
        int getY()
        {
            return y;
        }
};
int main()
{
    Point p(10,20);
    cout<<p.getX()<<" "<<p.getY()<<endl;
    cout<< p.setX(1000).getX();
    return 0;
}

I am returning pointer object from setX. And p.setX will first modify the value of x and then it will return a copy of object(p) from it. Since this is a copy then why my answer is 1000 in p.setX(1000).getx(). Since setX will modify the value of x in original object p.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • Btw `#include using namespace std;` indicates a bad book /teacher. You modify x then you create a copy, so the copy also has 1000 to x. – Michael Chourdakis Aug 07 '21 at 05:14
  • okay that means it first create a copy object and then copy value from original p. So that means I am not returning original object from setX I am returning copy of p. Correct me if I am wrong? – Deepak soni Aug 07 '21 at 05:18

1 Answers1

0

I am returning pointer object from setX

No you aren't. You are returning an instance of the class Point.

why my answer is 1000

Because you return a copy of an object whose member has the value 1000.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • okay that means inside setX , object of Point class will be created and value will be copied from original object. That's why getX() is giving answer as 1000. – Deepak soni Aug 07 '21 at 05:14