Thursday 5 April 2012

Operator chaining

Operator chaining enables repetitive use of some operator on the same object within the same expression.
One typical example is usage of the stream insertion operator (operator<<) on the std::cout stream object:

Insertion operator is left-associative so the statement above can be interpreted (or written) like this:

Another example would be chained assignment operator (operator=) defined for type std::string:

Assignment operator is right-associative so the statement with chain can be interpreted (or written) like this:

If we have some custom class C and want to enable assignment operator chaining we need to make sure that operator= returns a non-const reference to the object it is being executed on. Compiler-generated (implicit) assignment operator meets this requirement so we can rely on it, or, if we need to define our custom assignment operator, we need to make it returning such reference:

Output:

c1 = 987; c2 = 987; c3 = 987

If we want to keep operator= enabled but want to disable chaining, we need to make operator= returning void:

The following code:

will generate compiler error: error C2679: binary '=' : no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion), but the following code:

will be fine.

Links and References:
Operator overloading (Wiki)
Why does overloaded assignment operator return reference to class?
Why = Returns a Reference
Overloading assignment operator
C++ Operator Overloading Guidelines

No comments: