mardi 14 juin 2016

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).


Aucun commentaire:

Enregistrer un commentaire