Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return void or reference to self?

Given the following class:

struct Object {
    int x, y;
    void addtoall( int value ){ x += value; y += value; };
    Object& addtoall( int value ){ x += value; y += value; return *this; };
};

What is the difference between the two member functions?

I understand that returning a reference to self is required for some operator overloads (e.g: operator+= ), but excluding operator overloading, is it necessary? If not, when would you want or need to return the reference to self as opposed to returning void?

I apologize if this could be found via google-fu, or is a very basic question, but I wasn't sure what exactly to search (and not for lack of trying).

like image 818
WeRelic Avatar asked Jan 24 '26 09:01

WeRelic


1 Answers

What is the difference between the two member functions?

The function returning a reference to the instance can be chained when called like

Object o;
o.addtoall(5).addtoall(6).addtoall(7);

If this is useful depends on the actual use case, but it's often used to develop so called domain specific language syntax.

like image 118
πάντα ῥεῖ Avatar answered Jan 26 '26 22:01

πάντα ῥεῖ