O'Reilly logo

C++ In a Nutshell by Ray Lischner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required