1

I was checking a book of c++ and the put a function that is designed to make the class functions cascadable. In this book they conventionally make function inside the class to return a reference of the class rather than the class value. I tested returning a class by value or by reference and they both do the same. What is the difference?


#include<iostream>

using namespace std;
/*class with method cascading enabled functions*/
class a{
    private:
        float x;
    public:
        a& set(float x){
            this->x = x;
            return *this;
        }
        a& get(float& x){
            x = this->x;
            return *this;
        }
        a print(){
            cout << "x = " << x << endl;
            return *this;
        }
};

int main(){
    a A;
    A.set(13.0).print();
    return 0;
}

result

PS J:\c-c++> g++ -o qstn question1.cpp
PS J:\c-c++> .\qstn
x = 13

as you will notice this code work as spected. But happens here in detail?

1 Answers1

1

First read What's the difference between passing by reference vs. passing by value?

Now that you're done reading, let's try a slightly more complicated example so we can really see the difference:

int main(){
    a A;
    A.set(13.0).set(42).print();
    A.print();
    return 0;
}

If we return by reference A will be modified by set(13.0) and then A is returned and modified again by set(42). Output will be

x = 42
x = 42

but if we return by value A will be modified by set(13.0) and then a new temporary a that is a copy of A will be returned. This copy is modified by set(42), not A. Output will be

x = 42
x = 13

We have failed to cascade.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • Thanks. That's a good answer. It is the difference between returning a copy or a reference to it self, is it? – 96Fetuchini Sep 07 '22 at 16:13
  • Yes. `A` and the temporary copy of `A` look the same, they have the same value, but they are different objects with no connection between the two. Which option you chose depends on exactly what you want. Sometimes you want a copy, but if you want to keep using the same object through a chain of events, use a reference. [The temporary copy also has an extremely short lifetime](https://en.cppreference.com/w/cpp/language/lifetime). If you don't save it to something, whatever work you performed on it ,other than [side effects](https://stackoverflow.com/questions/9563600), is lost. – user4581301 Sep 07 '22 at 17:57