Benefit of function returning reference to object vs void?

Hi all,

I'm kind of just wondering what the benefit is of having an object as a return type, vs just using void. If I were doing something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Stack & push(double x){

    data[size] = x;
    size++;
    return *this;
}

void push(double x){

data[size] = x;
size++;

}


My professor is kind of in love with having the object as a return type whenever the function doesn't have anything useful to return, so I'm just wondering what the benefits are.

Thanks.
Last edited on
Returning a reference to *this lets you do
 
stack.push(0).push(3).push(51);
Meh.
It'd look nicer if you also overloaded operator<<():
1
2
3
4
5
6
7
8
Stack &operator<<(double x){
    this->push(x);
    return *this;
}

//...

stack << 0 << 3 << 51;
Last edited on
Thanks helios, not only did I not know that, but I was doing method chaining for a while now, without knowing why I was able to do it. Thanks for clearing that up.
Topic archived. No new replies allowed.