Professional Documents
Culture Documents
BSCS 208 - AOOP - Lecture 4b - Operator Overloading
BSCS 208 - AOOP - Lecture 4b - Operator Overloading
BSCS 208 - AOOP - Lecture 4b - Operator Overloading
Object Oriented
Programming
Lecture 4b - Operator
overloading
1
Operator overloading
Operator overloading
• Allows you to provide an intuitive interface to users of
your class. It allows C++ operators to have user-
defined meanings on classes.
Benefits of operator overloading
• By overloading standard operators on a class, you can
exploit the intuition of the users of that class. This lets
users program in the language of the problem domain
rather than in the language of the machine.
• The ultimate goal is to reduce both the learning curve
and the defect rate.
2
Operator overloading – cont’d
Examples of operator overloading
• myString + yourString might concatenate two
std::string objects
• myDate++ might increment a Date object
• a * b might multiply two Number objects
• a[i] might access an element of an Array object
• x = *p might dereference a "smart pointer" that "points"
to a disk record — it could seek to the location on disk
where p "points" and return the appropriate record into
x
3
Operator overloading – cont’d
Disadvantages of operator overloading
• Operator overloading makes life easier for the users of
a class, not for the developer of the class
• Operator overloading syntax isn't supposed to make
life easier for the developer of a class. It's supposed to
make life easier for the users of the class:
int main()
{
Array a;
a[3] = 4;
}
4
Operator overloading – cont’d
Operator overloading in Java
• Java does not allow operator overloading unlike C++.
The designers of Java decided that overloaded
operators are very confusing and counterproductive
for those who will maintain the code
• Although operator overloading is powerful, Java
designers argued that their disadvantages outweigh
their advantages, and therefore decided not to include
them in the language
5
Operator overloading – cont’d
For example, operator overloading assumes
that you can change the meaning of an
operator e.g. you can change the meaning of
the “+” operator to perform subtraction. Clearly
this can be very confusing to other
programmers who may try to maintain your
class later
The exception is the “+” which Java overloads
for math addition, string concatenation and
even matrix addition
6
Operator overloading – cont’d
Example
• Math addition:
x = 3+5;
• String concatenation:
String firstName = “Joe”, lastName = “Smith”;
String name = firstName + “ ” + lastName;
Expected output = Joe Smith
• Matrix addition:
matrix a, b, c;
c = a + b;