Operator Overloading

For user-defined types (classes and enumerations), you can define alternate behavior for the C++ operators. This is called overloading the operators. You cannot define new operators, and not all operators can be overloaded. Table 5-2 lists all the operators and indicates which can be overloaded. For these, it shows whether the overload must be a member function. Overloaded operators that are implemented as member functions must be nonstatic member functions.

Table 5-2. Operators and overloading

Operator

Meaning

Overloading permitted?

Must be member function?

+

Addition, unary plus

yes

no

&

Address of

yes

no

[]

Array subscript

yes

yes

&=

Assign bitwise and

yes

no

^=

Assign bitwise exclusive or

yes

no

|=

Assign bitwise or

yes

no

-=

Assign difference

yes

no

<<=

Assign left shift

yes

no

=

Assignment

yes

yes

*=

Assign product

yes

no

/=

Assign quotient

yes

no

%=

Assign remainder

yes

no

>>=

Assign right shift

yes

no

+=

Assign sum

yes

no

&

Bitwise and

yes

no

~

Bitwise complement

yes

no

^

Bitwise exclusive or

yes

no

|

Bitwise or

yes

no

? :

Conditional

no

N/A

new

Create dynamic object

yes

no

new[]

Create dynamic array

yes

no

--

Decrement

yes

no

delete

Destroy dynamic object

yes

no

delete[]

Destroy dynamic array

yes

no

/

Division

yes

no

==

Equal

yes

no

( )

Function call

yes

yes

>

Greater than

yes

no

>=

Greater than or equal

yes

no

++

Increment

yes

no

<<

Left shift

yes

no

<

Less than

yes

no

<=

Less than or equal

yes

no

&&

Logical and

yes

no

!

Logical complement

yes

no

||

Logical or

yes

no

.*

Member reference

no

N/A

->*

Member reference

yes

yes

.

Member ...

Get C++ In a Nutshell 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.