maandag 2 juli 2007

operator overloading

total = coding.operator+(fixing); // function notation

But naming the method operator+() also lets you use operator notation:

total = coding + fixing; // operator notation

Either notation invokes the operator+() method. Note that with the operator notation, the object to the left of the operator (coding in this case) is the invoking object, and the object to the right (fixing in this case) is the one passed as an argument.

Can you add more than two objects? For example, if t1, t2, t3 and t4 are all Time objects, can you do the following?

t4 = t1 + t2 + t3; // valid?

The way to answer this is to consider how the statement gets translated into function calls.
Because addition is a left-to-right operator, the statement is first translated to this:

t4 = t1.operator+(t2 + t3); // valid?

Then the function argument is itself translated to a function call, giving the following:

t4 = t1.operator+(t2.operator+(t3)); // valid? YES

The function call t2.operator+(t3) returns a Time object that represents the sum of t2 and t3. This object then becomes the object of the t1.operator+() function call, and that call returns the sum of t1 and the Time object that represents the sim of t2 and t3. In short, the final return value is the sum of t1, t2 and t3, just as desired.