C++ Operator Overloading 2
C++ Operator Overloading 2
Prepared By
Dr. Chemmalar Selvi G.
VIT India
chemmalarselvi.g@vit.ac.in
Why we need operator overloading?
• Operators work with operands.
– For example we can use increment operator
with int values or int type variables like count ++.
– But, we can’t use these operator with objects, directly
– Consider we want to use this with object : obj1 as
obj++ that increments all the variables inside the class
by 100.
– We can’t do that simply as obj++ as these operators
don’t work with classes.
• However, we can overload these operators and
give them special meanings to run along with
object and write code to increment the value by
100 for all variables.
How to define Overloading?
• We must use keyword operator before the
operator we want to overload
• It works as a function itself thus, return type must
also be defined
• Example –
:: .* . ?:
• Assignment Operators working with Objects are
by default overloaded by C++
• When we write a class in C++ the compiler by
default automatically creates its own version of
operator overloading for assignment operator.
What this essentially does is, consider two
objects obj1 and obj2if we simply want to copy all
the data values for obj1 into obj2 we can directly
use assignment operator as obj1 = obj2
Implementing Operator Overloading