C++ Operator Overloading
C++ Operator Overloading
C++ Operator Overloading
Operator Overloading
• Examples:
– << bitwise left-shift operator and stream insertion
operator
– >> bitwise right-shift operator and stream extraction
operator
– + & - overloaded to perform differently depending on
their context in integer, floating-point arithmetic and
pointer arithmetic
• Prototype:
Return type operator<operator-to-be-overloaded>(parameter
list)
{ …}
• Operators ‘=‘ and ‘&’ can be used with any class without
explicit overloading. The default behaviour of ‘=‘ is
member-wise assignment and ‘&’ is used to return
address of the object in memory.
Introduction Contd…
• Overloading is most appropriate for mathematical
classes. These often require that a substantial set of
operators be overloaded to ensure consistency with the
way these mathematical classes are handled in the real
world. For e.g. a complex number class must have
other operators besides addition.
• //array example
• Example declarations:
Date d1;
Pre-incrementing
Member function:
++d1 = d1.operator(); Prototype Date operator ++()
Non-member function:
++d1 = operator(d1); Prototypefriend Date operator++(Date
&)
Post-incrementing
Member function:
d1++ = d1.operator(0); Prototype Date operator ++(int)
Non-member function:
d1 ++= d1.operator(d1,0); Prototypefriend Date
operator++(Date &,int)
Overloading ++ and -- …
• Similar is the case for pre-and post decrementing
• http://www.cplusplus-naturally.blog
• http://zainvi.sf.googlepages.com/in
• http://www.computer-science-note
u
Y o
an k
T h
n s ?
s t i o s ?
u e t io n
Q e s
g g
Su