TITLE: returning self reference from mutators (Newsgroups: comp.lang.c++.moderated, 28 Mar 97) CAMBELL: Mike Campbell |> I've recently seen, and have become rather accustomed to, mutators |> returning a reference to this. |> |> class foo // has members f, i, and s (float, int, and string) |> { |> public: |> foo& F(float in) { _f = in; return *this; } |> ... |> |> private: |> float _f; |> ... |> }; |> |> |> This allows one to write: |> |> foo obj; obj.F(3.14).I(2).S("bar"); |> |> to set multiple members in one line. |> |> Am I being seduced by something evil, or is this a Common Way To Do |> It(tm)? KANZE: James Kanze Or both:-). Seriously, I find that in general, this probably doesn't do much for the maintainability, but in specific cases, it is a good solution. I can think of at least one case where it is certainly appropriate: for handling argument lists. A typical example would be a window descripter. The constructor creates the object (with default parameters) and you add the custom parameters before passing it, e.g.: createWindow( WindowParameters( defaultWindowStyle ) .backgroundColor( "chartreuse" ) .foregroundColor( "magenta" ) .name( "sickening" ) ) ; I use this in my GB_Format class, for example: cout << GB_Format( "The value is %6.2f" ).with( theValue ) << endl ; For that matter, although the spelling is different, this is exactly what is happening in: cout << "Some text" << aNumber << endl ; The above is actually: cout.operator<<( "Some text" ).operator<<( aNumber ).operator<<( endl ) ; Despite all this, I think that such chaining should be the exception, not the rule. (Pete Becker mentions that he hasn't seen this idiom much in production code. I would guess that he wasn't considering the use of operator<<.)