lagertha6
lagertha6

Reputation: 39

c++ pointers return 0 value

Im pretty new to C++ and I have problem with pointers. Can someone please explain me how does this code return 0 for y, instead of 20?

#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; cout << "hello"; return *this; } 
        Test setY(int b) { y = b; cout << "world"; return *this; } 
        void print() { cout << "x = " << x << " y = " << y << endl; } 
    }; 

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

Upvotes: 2

Views: 309

Answers (3)

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3323

If you want to chain calls to Test, your setters need to return a reference on Test instance. If you do not return a reference to the object, it is not udpated, a copy of it is updated. Without the reference what you wrote is equivalent to:

Test tmp = obj1.setX(10);
tmp.setY(20)
obj1.print()

(tmp is a "local" variable created by the compiler)

Fixed code below:

#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; cout << "hello"; return *this; } 
  Test &setY(int b) { y = b; cout << "world"; return *this; } 
  void print() { cout << "x = " << x << " y = " << y << endl; } 
}; 
int main() 
{ 
  Test obj1; 
  obj1.setX(10).setY(20);
  obj1.print(); 
  return 0; 
} 

Upvotes: 2

Jasper Kent
Jasper Kent

Reputation: 3676

Your methods are returning copies of the test object.

Test setX(int a) { x = a; cout << "hello"; return *this; } 
Test setY(int b) { y = b; cout << "world"; return *this; } 

So obj1.setX(10) applies to the original, but then .SetY(20) applies to the copy.

You need to return by reference:

Test& setX(int a) { x = a; cout << "hello"; return *this; } 
Test& setY(int b) { y = b; cout << "world"; return *this; } 

Upvotes: 5

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

You are trying to implement a design called "function chaining". To do this, you must return a reference to the current object, not a brand new object:

  Test& setX(int a) { x = a; cout << "hello"; return *this; } 
  Test& setY(int b) { y = b; cout << "world"; return *this; } 

Since you are returning the current object, this will now work. Your example was returning a brand new Test object, which is why you were seeing 0 as the output.

Upvotes: 4

Related Questions