Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Advanced Functions 317

10


cannot be changed. You cannot make up new operators, so you cannot declare **to be
the “power of” operator.


Arity refers to how many terms are used in the operator. Some C++ operators are unary
and use only one term (myValue++). Some operators are binary and use two terms (a+b).
Only one operator is ternary and uses three terms. The ?operator is often called the
ternary operator because it is the only ternary operator in C++ (a > b? x : y).


What to Overload ..........................................................................................


Operator overloading is one of the aspects of C++ most overused and abused by new
programmers. It is tempting to create new and interesting uses for some of the more
obscure operators, but these invariably lead to code that is confusing and difficult to read.


Of course, making the +operator subtract and the *operator add can be fun, but no pro-
fessional programmer would do that. The greater danger lies in the well-intentioned but
idiosyncratic use of an operator—using +to mean concatenate a series of letters or /to
mean split a string. There is good reason to consider these uses, but there is even better
reason to proceed with caution. Remember, the goal of overloading operators is to
increase usability and understanding.


DOuse operator overloading when it
will clarify the program.
DOreturn an object of the class from
overloaded operators.

DON’Tcreate counterintuitive operator
behaviors.
DON’Tconfuse the prefix and postfix
operators, especially when overloading.

DO DON’T


The Assignment Operator ..............................................................................


The fourth and final function that is supplied by the compiler, if you don’t specify one, is
the assignment operator (operator=()). This operator is called whenever you assign to
an object. For example:


Cat catOne(5,7);
Cat catTwo(3,4);
// ... other code here
catTwo = catOne;


Here,catOneis created and initialized with itsAgeequal to 5 and itsWeightequal to 7.
catTwois then created and assigned the values 3 and 4.

Free download pdf