C++ Operator Overloading
Prepared By
Dr. Chemmalar Selvi G.
VIT India
[email protected]
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 –
• Note – Overloaded operators will only work with
objects of the class under which they are defined.
Operators for which overloading is
allowed –
+ – * / % ^
& | ~ ! , =
< > <= >= ++ —
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
Operators for which Overloading is not
allowed –
:: .* . ?:
• 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
• Operator overloading can be done by
implementing a function which can be :
• Member Function
• Non-Member Function
• Friend Function
Overloading Unary Operator using a Friend function
Overloading Binary plus (+) operator using non-member function
PS using Operator Overloading
Programs to Overload Unary & Binary Operators as Member
Function & Non Member Function. A. Unary operator as
member function B. Binary operator as non member function
A: Write a C++ program to count the number of persons inside
a bank, by increasing count whenever a person enters a bank,
using an increment(++) operator overloading function, and
decrease the count whenever a person leaves the bank using
a decrement(--) operator overloading function inside a class
B: Write a C++ program to create two objects of a class called
company and add their data members using an operator
overloaded function for ‘+’ operator and ‘-‘operator
PS using Operator Overloading
Thank you