Item 10: Have assignment operators return a reference to *thisOne of the interesting things about assignments is that you can chain them together: int x, y, z; x = y = z = 15; // chain of assignments Also interesting is that assignment is right-associative, so the above assignment chain is parsed like this: x = (y = (z = 15)); Here, 15 is assigned to z, then the result of that assignment (the updated z) is assigned to y, then the result of that assignment (the updated y) is assigned to x. The way this is implemented is that assignment returns a reference to its left-hand argument, and that's the convention you should follow when you implement assignment operators for your classes: class Widget { public: ... Widget& operator=(const Widget& rhs) // return type is a reference to { // the current class ... return *this; // return the left-hand object } ... }; This convention applies to all assignment operators, not just the standard form shown above. Hence: class Widget { public: ... Widget& operator+=(const Widget& rhs // the convention applies to { // +=, -=, *=, etc. ... return *this; } Widget& operator=(int rhs) // it applies even if the { // operator's parameter type ... // is unconventional return *this; } ... }; This is only a convention; code that doesn't follow it will compile. However, the convention is followed by all the built-in types as well as by all the types in (or soon to be in see Item54) the standard library (e.g., string, vector, complex, tr1::shared_ptr, etc.). Unless you have a good reason for doing things differently, don't. Things to Remember
|