Lecture 8: Operator Overloading


Definition of Operator Overloading

Up to this point in the discussion of C++, the programmer could define operations on structure instance and class objects by using a function. For example:

image from book

 c = add(a,b); 

image from book

where a, b and c are instances of some structure or a class. However, this is using non-standard operators. C++ permits the programmer to use some of the standard operators in a more natural way using what is called: operator overloading. However, to do this requires that the programmer observe some restrictions.

To define operator overloading on class objects requires that the operator:

  • is a system operator.

  • maintains the system order of precedence

  • can not change type: i.e. between unary and binary operators

  • has at least one operand that is a class object.

  • is non static.

  • has in the operator's definition the keyword: operator

In addition, the programmer should take care how the operators are defined and that the operators should model their real world use. The permissible operators for overloading are:

image from book

Open table as spreadsheet

OVERLOADABLE OPERATORS

+

-

*

/

%

^

&

|

~

!

,

=

<

>

<=

>=

++

--

_

<<

>>

==

!=

&&

||

+=

-=

/=

<<=

>>=

[ ]

( )

->

->*

 

new

delete

   

image from book

While most of the C++ operators can be overloaded, the dot operator (.) and some other operators can not be overloaded. The discussion in this lecture will only cover a few of the operators above.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net