Difference between these functions.

May 20, 2020 at 1:30pm
Can you help me understand the difference between setx, sety, and setz functions please. I am especially confused about the Test &setx(int a), and what reference symbol purpose is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 #include <iostream>
using namespace std;

class Test
{
    private:
        int x;
    public:
        Test(int t) : x(t) {};
        Test &setx(int a)
        {
            x = a;
            return *this;
        }
        Test sety(int a)
        {
            x = a;
            return *this;
        }
        void setz(int a)
        {
            x = a;
        }
        void print() { cout << "x = " << x << endl;}
};

int main()
{
 Test tst(5);
 tst.print(); 
 tst.setx(6);
 tst.print();
 tst.sety(7);
 tst.print();
return 0;
};
May 20, 2020 at 1:36pm
All three of them set x to the particular a value given.
The difference is in their result types.

setx returns "*this" (the current class's object) by reference
sety returns "*this" by value, or in other words by copying it.
setz doesn't return anything.

In your example, this behavior has no purpose because it is not used at all.
But what you could do is something like this instead:
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
 Test tst(5);
 tst.print(); 
 
 tst.setx(6).setz(100);
 tst.print();
 
 tst.sety(7).setz(200);
 tst.print();
 return 0;
};

The output is:
x = 5
x = 100
x = 7

Now you may ask yourself, why is x = 7 on that third line, if I set it to 200?
It's because sety returns a Test object by value, which copies it. The object being assigned to in the setz(200) call is a temporary unnamed object that doesn't affect the existing tst object.
Last edited on May 20, 2020 at 1:38pm
Topic archived. No new replies allowed.