Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 16

How to overload the function call operator

How to overload the dereferencing operators (* and ->)

How to write conversion operators

How to overload the memory allocation and deallocation operators

Over view of Operator Overloading

As Chapter 1 reviewed, operators in C++ are symbols such as +, <, *, and <<. They work on built-in types such as int and double to allow you to perform arithmetic, logical, and other operations. There are also operators such as -> and & that allow you to dereference pointers. The concept of operators in C++ is broad, and even includes [] (array index), () (function call), and the memory allocation and deallocation routines.

Operator overloading allows you to change the behavior of language operators for your classes. However, this capability comes with rules, limitations, and choices.

Why Overload Operators?

Before learning how to overload operators, you probably want to know why you would ever want to do so. The reasons vary for the different operators, but the general guiding principle is to make your classes behave like built-in types. The closer your classes are to built-in types, the easier they will be for clients to use. For example, if you want to write a class to represent fractions, it’s quite helpful to have the ability to define what +, -, *, and / mean when applied to objects of that class.

The second reason to overload operators is to gain greater control over behavior in your program. For example, you can overload memory allocation and deallocation routines for your classes to specify exactly how memory should be distributed and reclaimed for each new object.

It’s important to emphasize that operator overloading doesn’t necessarily make things easier for you as the class developer; its main purpose is to make things easier for clients of the class.

Limitations to Operator Overloading

Here is a list of things you cannot do when you overload operators:

You cannot add new operator symbols. You can only redefine the meanings of operators already in the language. The table in the “Summary of Overloadable Operators” section lists all of the operators that you can overload.

There are a few operators that you cannot overload, such as . (member access in an object), :: (scope resolution operator), sizeof, ?: (the ternary operator), and a few others. The table lists all the operators that you can overload. The operators that you can’t overload are usually not those you would care to overload anyway, so we don’t think you’ll find this restriction limiting.

You cannot change the arity of the operator. The arity describes the number of arguments, or operands, associated with the operator. Unary operators, such as ++, work on only one operand. Binary operators, such as +, work on two operands. There is only one ternary operator: ?:. The

432

Overloading C++ Operators

main place where this limitation might bother you is when overloading [] (array brackets), as discussed below.

You cannot change the precedence or associativity of the operator. These rules determine in which order operators are evaluated in a statement. Again, this constraint shouldn’t be cause for concern in most programs because there are rarely benefits to changing the order of evaluation.

You cannot redefine operators for built-in types. The operator must be a method in a class, or at least one of the arguments to a global overloaded operator function must be a user-defined type (e.g., a class). This means that you can’t do something ridiculous such as redefine + for ints to mean subtraction (though you could do so for your classes). The one exception to this rule is the memory allocation and deallocation routines; you can replace the global routines for all memory allocation in your program.

Some of the operators already mean two different things. For example, the operator can be used as a binary operator, as in x = y - z or as a unary operator, as in x = -y;. The * operator can be used for multiplication or for dereferencing a pointer. The << operator is the insertion operator or the left-shift operator, depending on context. You can overload both meanings of operators with dual meanings.

Choices in Operator Overloading

When you overload an operator, you write a function or method with the name operatorX, where X is the symbol for some operator. For example, in Chapter 9, you saw operator+ declared for SpreadsheetCell objects like this:

friend const SpreadsheetCell operator+(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs);

There are several choices involved in each overloaded operator function or method you write.

Method or Global Function

First, you must decide whether your operator should be a method of your class or a global function (usually a friend of the class). How do you choose? First, you need to understand the difference between these two choices. When the operator is a method of a class, the left-hand-side of the operator expression must always be an object of that class. If you write a global function, the left-hand-side can be an object of a different type.

There are three different types of operators:

Operators that must be methods. The C++ language requires some operators to be methods of a class because they don’t make sense outside of a class. For example, operator= is tied so closely to the class that it can’t exist anywhere else. The table in the “Summary of Overloadable Operators” section lists those operators that must be methods. For these, the choice of method or global function is simple! However, most operators do not impose this requirement.

Operators that must be global functions. Whenever you need to allow the left-hand side of the operator to be a variable of a different type from your class, you must make the operator a global function. This rule applies specifically to operator<< and operator>>, where the left-hand side is the iostream object, not an object of your class. Additionally, commutative operators like binary + and should allow variables that are not objects of your class on the left-hand side. This problem was explained previously in Chapter 9.

433

Chapter 16

Operators that can be either methods or global functions. There is some disagreement in the C++ community on whether it’s better to write methods or global functions to overload operators. However, we recommend the following rule: make every operator a method unless you must make it a global function as described previously. One major advantage to this rule is that methods can be virtual, but friend functions cannot. Therefore, when you plan to write overloaded operators in an inheritance tree, you should make them methods if possible.

When you write an overloaded operator as a method, you should mark the entire method const if it doesn’t change the object. That way, it can be called on const objects.

Choosing Argument Types

You are somewhat limited in your choice of argument types because you can’t usually change the number of arguments (although there are exceptions, which are explained later in this chapter). For example, operator+ must always have two arguments if it is a global function; one argument if it’s a method.

The compiler issues an error if it differs from this standard. In this sense, the operator functions are different from normal functions, which you can overload with any number of parameters. Additionally, although you can write the operator for whichever types you want, the choice is usually constrained by the class for which you are writing the operator. For example, if you want to implement addition for class T, you wouldn’t write an operator+ that takes two strings! The real choice arises when you try to determine whether to take parameters by value or by reference, and whether or not to make them const.

The choice of value vs. reference is easy: you should take every parameter by reference. As explained in Chapters 9 and 12, never pass objects by value if you can pass-by-reference instead!

The const decision is also trivial: mark every parameter const unless you actually modify it. The table in the “Summary of Overloadable Operators” section shows sample prototypes for each operator, with the arguments marked const and reference as appropriate.

Choosing Return Types

Recall that C++ doesn’t determine overload resolution based on return type. Thus, you can specify any return type you want when you write overloaded operators. However, just because you can do something doesn’t mean you should do it. This flexibility implies that you could write confusing code in which comparison operators return pointers, and arithmetic operators return bools! However, you shouldn’t do that. Instead, you should write your overloaded operators such that they return the same types as the operators do for the built-in types. If you write a comparison operator, return a bool. If you write an arithmetic operator, return an object representing the result of the arithmetic. Sometimes the return type is not obvious at first. For example, as you learned in Chapter 8, operator= should return a reference to the object on which it’s called in order to support nested assignment. Other operators have similarly tricky return types, all of which are summarized in the table in the “Summary of Overloadable Operators” section.

The same choices of reference and const apply to return types as well. However, for return values, the choices are more difficult. The general rule for value or reference is to return a reference if you can; otherwise, return a value. How do you know when you can return a reference? This choice applies only to operators that return objects: the choice is moot for the comparison operators that return bool, the conversion operators that have no return type, and the function call operator, which may return any type you want. If your operator constructs a new object, then you must return that new object by value. If it

434

Overloading C++ Operators

does not construct a new object, you can return a reference to the object on which the operator is called, or one of its arguments. The table in the “Summary of Overloadable Operators” section shows examples.

A return value that can be modified as an lvalue (the left-hand-side of an assignment expression) must be non-const. Otherwise, it should be const. More operators than you might think at first return lvalues, including all of the assignment operators (operator=, operator+=, operator-=, etc.).

If you are in doubt about the appropriate return type, simply consult the table in the “Summary of Overloadable Operators” section.

Choosing Behavior

You can provide whichever implementation you want in an overloaded operator. For example, you could write an operator+ that launches a game of Scrabble. However, as described in Chapter 5, you should generally constrain your implementations to provide behaviors that clients expect. Write operator+ so that it performs addition, or something like addition, such as string concatenation.

This chapter explains how you should implement your overloaded operators. In exceptional circumstances, you might want to differ from these recommendations, but, in general, you should follow the standard patterns.

Operators You Shouldn’t Overload

There are a few operators that it is rarely a good idea to overload, even though it is permitted. Specifically, the address-of operator (operator&) is not particularly useful to overload, and leads to confusion if you do because you are changing fundamental language behavior (taking addresses of variables) in potentially unexpected ways.

Additionally, you should avoid overloading the binary Boolean operators operator&& and operator|| because you lose C++’s short-circuit evaluation rules.

Finally, you should not overload the comma operator (operator,). Yes, you read that correctly: there really is a comma operator in C++. It’s also called the sequencing operator, and is used to separate two expressions in a single statement, while guaranteeing that they are evaluated left to right. There is rarely (if ever) a good reason to overload this operator.

Summary of Overloadable Operators

The following table lists all of the operators that you can overload, specifies whether they should be methods of the class or global friend functions, summarizes when you should (or should not) overload them, and provides sample prototypes, showing the proper return values.

This table should be a useful reference in the future when you want to sit down and write an overloaded operator. You’re bound to forget which return type you should use, and whether or not the function should be a method. We’re looking forward to referring to this table ourselves!

In this table, T is the name of the class for which the overloaded operator is written, and E is a different type (not the name of the class).

435

Chapter 16

 

 

Method or

 

 

 

Name or

Global Friend

When to

 

Operator

Category

Function

Overload

Sample Prototype

 

 

 

 

 

operator+

Binary

Global friend

Whenever you

friend const T

operator-

arithmetic

function

want to

operator+(const

operator*

 

recommended

provide these

T&, const T&);

operator/

 

 

operations for

 

operator%

 

 

your class

 

operator-

Unary

Method

Whenever you

const T operator-()

operator+

arithmetic

recommended

want to

const;

operator~

and bitwise

 

provide these

 

 

operators

 

operations for

 

 

 

 

your class

 

operator++

Increment

Method

Whenever you

T& operator++();

operator--

and

recommended

overload

 

 

decrement

 

binary + and -

const T

 

 

 

 

operator++(int);

operator=

Assignment

Method

Whenever

T& operator=(const

 

operator

required

you have

T&);

 

 

 

dynamically

 

 

 

 

allocated

 

 

 

 

memory in the

 

 

 

 

object or want

 

 

 

 

to prevent

 

 

 

 

assignment, as

 

 

 

 

described in

 

 

 

 

Chapter 9

 

operator+=

Shorthand

Method

Whenever you

T& operator+=(const

operator-=

arithmetic

recommended

overload the

T&);

operator*/

operator

 

binary

 

operator/=

assignments

 

arithmetic

 

operator%=

 

 

operators

 

operator<<

Binary bitwise

Global friend

Whenever you

friend const T

operator>>

operators

function

want to

operator<<(const

operator&

 

recommended

provide these

T&, const T&);

operator|

 

 

operations

 

operator^

 

 

 

 

operator<<=

Shorthand

Method

Whenever you

T& operator<<=

operator>>=

bitwise

recommended

overload the

(const T&);

operator&=

operator

 

binary bitwise

 

operator|=

assignments

 

operators

 

operator^=

 

 

 

 

 

 

 

 

 

436

Overloading C++ Operators

 

 

Method or

 

 

 

Name or

Global Friend

When to

 

Operator

Category

Function

Overload

Sample Prototype

 

 

 

 

 

operator<

Binary

Global friend

Whenever you

friend bool

operator>

comparison

function

want to

operator<(const T&,

operator<=

operators

recommended

provide these

const T&);

operator>=

 

 

operations

 

operator==

 

 

 

 

operator<<

I/O stream

Global friend

Whenever you

friend ostream

operator>>

operators

function

want to

&operator<<

 

(insertion and

recommended

provide these

(ostream&,

 

extraction)

 

operations

const T&);

 

 

 

 

friend istream

 

 

 

 

&operator>>

 

 

 

 

(istream&, T&);

operator!

Boolean

Member

Rarely; use

bool operator!()

 

negation

function

bool or void*

const;

 

operator

recommended

conversion

 

 

 

 

instead

 

operator&&

Binary

Global friend

Rarely

friend bool

operator||

Boolean

function

 

operator&&(const T&

 

operators

recommended

 

lhs, const T& rhs);

 

 

 

 

friend bool

 

 

 

 

operator||(const T&

 

 

 

 

lhs, const T& rhs);

operator[]

Subscripting

Method

When you

E& operator[](int);

 

(array index)

required

want to

 

 

operator

 

support

const E&

 

 

 

subscripting:

operator[](int)

 

 

 

in array-like

const;

 

 

 

classes

 

operator()

Function call

Method

When you

Return type and

 

operator

required

want objects

arguments can vary; see

 

 

 

to behave like

examples in this chapter

 

 

 

function

 

 

 

 

pointers

 

operator new

Memory

Method

When you

void* operator

operator new[]

allocation

recommended

want to

new(size_t size)

 

routines

 

control

throw(bad_alloc);

 

 

 

memory

 

 

 

 

allocation for

void* operator

 

 

 

your classes

new[](size_t size)

 

 

 

(rarely)

throw(bad_alloc);

 

 

 

 

 

Table continued on following page

437