Commutative Operators

Another reason why you might choose a non-member function to overload an operator is to enable the operator to be commutative. For example, suppose we have a fundamental type variable, number, of type long int, and an object bigInteger1, of class HugeInt (a class in which integers may be arbitrarily large rather than being limited by the machine word size of the underlying hardware). The addition operator (+) produces a temporary HugeInt object as the sum of a HugeInt and a long int (as in the expression bigInteger1 + number), or as the sum of a long int and a HugeInt (as in the expression number + bigInteger1). Thus, we require the addition operator to be commutative (exactly as it is with two fundamental-type operands). The problem is that the class object must appear on the left of the addition operator if that operator is to be overloaded as a member function. So, we also overload the operator as a non-member function to allow the HugeInt to appear on the right of the addition. The operator+ function that deals with the HugeInt on the left can still be a member function. The non-member function can simply swap its arguments and call the member function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.188.16