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:


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

1 comment:

micheal pan said...

BE SMART AND BECOME RICH IN LESS THAN 3DAYS....It all depends on how fast 
you can be to get the new PROGRAMMED blank ATM card that is capable of
hacking into any ATM machine,anywhere in the world. I got to know about 
this BLANK ATM CARD when I was searching for job online about a month 
ago..It has really changed my life for good and now I can say I'm rich and 
I can never be poor again. The least money I get in a day with it is about 
$50,000.(fifty thousand USD) Every now and then I keeping pumping money 
into my account. Though is illegal,there is no risk of being caught 
,because it has been programmed in such a way that it is not traceable,it 
also has a technique that makes it impossible for the CCTVs to detect 
you..For details on how to get yours today, email the hackers on : ( ). Tell your 
loved once too, and start to live large. That's the simple testimony of how 
my life changed for good...Love you all ...the email address again is ;