OPERATOR OVERLOADING

Operator overloading is a very important capability because it enables you to make standard C++ operators, such as +, -, *, and so on, work with objects of your own data types. It allows you to write a function that redefines an operator so that it performs a particular action when it’s used with objects of a class type. For example, you could redefine the operator < so that when it was used with objects of the CBox class, it would return true if the first CBox argument had a smaller volume than the second.

Operator overloading doesn’t allow you to invent new operators, nor can you change operator precedence, so your overloaded version of an operator will have the same priority in the sequence of evaluating an expression as the original operator. You can find the operator precedence table in Chapter 2 of this book and in the MSDN Library.

Although you can’t overload all the operators, the restrictions aren’t particularly oppressive. These are the operators that you can’t overload:

OPERATOR DEFINITION
:: The scope resolution operator
?: The conditional operator
. The direct member selection operator
sizeof The size-of operator
.* The de-reference pointer to class member operator

Anything else is fair game, which gives you quite a bit of scope. Obviously, it’s a good idea to ensure that your versions of the standard operators are reasonably consistent with their normal usage, or at least reasonably intuitive in their operation. It wouldn’t be ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.