Home > Software engineering >  return class by value or by reference
return class by value or by reference

Time:09-08

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?

CodePudding user response:

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.

  • Related