fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. // Returning copies
  5. class Test1
  6. {
  7. private:
  8. int x;
  9. int y;
  10. public:
  11. Test1 (int x = 0, int y = 0) { this->x = x; this->y = y; }
  12. Test1 setX(int a) { x = a; return *this; }
  13. Test1 setY(int b) { y = b; return *this; }
  14. void print() { cout << "x = " << x << " y = " << y << endl; }
  15. };
  16.  
  17. // Returning references
  18. class Test2
  19. {
  20. private:
  21. int x;
  22. int y;
  23. public:
  24. Test2 (int x = 0, int y = 0) { this->x = x; this->y = y; }
  25. Test2& setX(int a) { x = a; return *this; }
  26. Test2& setY(int b) { y = b; return *this; }
  27. void print() { cout << "x = " << x << " y = " << y << endl; }
  28. };
  29.  
  30. int main()
  31. {
  32. Test1 obj1;
  33. obj1.setX(10).setY(20);
  34. obj1.print();
  35.  
  36. Test2 obj2;
  37. obj2.setX(10).setY(20);
  38. obj2.print();
  39. }
  40.  
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
x = 10 y = 0
x = 10 y = 20