0% found this document useful (0 votes)
3 views45 pages

OOP04 Operator Overloading

The document provides an overview of operator overloading in Object Oriented Programming, specifically in C++. It explains how operators can be redefined for user-defined data types, the syntax for overloading operators, and the distinction between member and non-member functions for operator overloading. Additionally, it discusses the implications of overloading operators like ++, --, and assignment operators, along with examples of their implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views45 pages

OOP04 Operator Overloading

The document provides an overview of operator overloading in Object Oriented Programming, specifically in C++. It explains how operators can be redefined for user-defined data types, the syntax for overloading operators, and the distinction between member and non-member functions for operator overloading. Additionally, it discusses the implications of overloading operators like ++, --, and assignment operators, along with examples of their implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Object Oriented Programming

Object Oriented Programming 04:

Operator Overloading

1. Introduction to Operator Overloading 2.


Implementing Overloaded Operators 3.
Invoking Objects
4. Overloading ++ and –
5. Overloading == and [ ] Dr. Imran
Ihsan Ph.D. in Knowledge Engineering Associate Professor
6. Overloading From Native Data Types 7.
Overloading << and >>
Object Oriented Programming
2
04-01
Introduction to Operator Overloading
04 Operator Overloading
Object Oriented Programming 04: Operator Overloading3

Operator Overloading
The method of defining additional meanings for operators is known as operator overloading
Enables an operator to perform different operations depending upon the type of operands The
basic operators i.e. +, -, *, / normally works with basic types i.e. double, float, int, long. (C++) So,
how can these operators can be applied to user-defined data types?

Motivation:
Don’t want to create new operators for user-defined data types
Conclusively, Operator overloading:
Enabling C++’s operators to work with class objects
Using traditional operators with user-defined objects
Requires great care; when overloading is misused, program difficult to understand

Examples of already overloaded operators:


Operator << is both the stream-insertion operator and the bitwise left-shift operator
Object Oriented Programming
Examples (Already Overloaded
double division
04: Operator Overloading
4

Operators)
type int / type int type long / type long

9/5 9L / 5L

Operator performs Operator performs


int division long division

type double / type double type float / type float

9.0 / 5.0 9.0f / 5.0f

Operator performs Operator performs


float division Can be independent function
Object Oriented Programming
(except for the following operators: ( ), [ ], -> or
How to Overload an Operator? any of the assignment operators) Can be a
An operator can be overloaded by declaring a class’s member function (must be non-static)
special member function in the class Name of
the member function is operator that is Member function:
followed by operator symbol e.g., operator+, 04: Operator Overloading 5

operator/, etc.
If the left operand of that class is an object of the same class, then the overloaded operator
is said to be implemented by a member function.
Non-member function:
If the left operand of that class is an object of a different class, then the overloaded operator
is said to be implemented by a non-member function
Object Oriented Programming
Overload as Member or
operator, implement it as a member function.
04: Operator Overloading 6

Non-Member Function If it is a unary

If a binary operator treats both operands equally (it leaves them unchanged), implement
this operator as a non-member function.

If a binary operator does not treat both of its operands equally (usually it will change its left
operand), it might be useful to make it a member function of its left operand’s type

the << operator (when used for stream output, not bit shifting) gets an ostream as its first
parameter, so it can't be a member of your class.
Object Oriented Programming Object Oriented Programming

Syntax to Overload an Operator Operator Overloading


returnType operator opsymbol (parameters){ } Operators are really functions
↑↑↑↑ They have arguments, they return values
any type Keyword operator symbol function body The only difference is that their names take on a
specific form: Operator+, operator[ ]
return-type may be whatever the operator
returns Operator symbol may be any Overloading provides concise notation:
overloadable operator // without operator overloading
object2 = object1.add(object2);

Example:
// with operator overloading
void operator+ (parameters) { }
object2 = object2 + object1;
04: Operator Overloading 8
↑↑↑↑ Object Oriented Programming
any type keyword/operator symbol function body
04: Operator Overloading 7
Restriction on Operator Operator =, Operator &
Overloading Operator = and operator & are overloaded

With operator overloading we cannot change: implicitly for every class, so, they can be used for
How operators act on built-in data types: each class objects.
i.e., cannot change integer addition
Precedence of operator (order of evaluation)
Use parentheses to force order-of-operations operator = performs member-wise copy of the
Association rules (left-to-right or right-to-left
data members. operator & returns the address of
evaluation) Number of operands
the object in memory.
i.e., & is unary, only acts on one operand
04: Operator Overloading 10
Cannot create new operators Object Oriented Programming
Operators must be overloaded explicitly:
i.e., Overloading + , does not overload +=
Function Overloading
04: Operator Overloading 11
04: Operator Overloading 9
Object Oriented Programming
An overloaded function is one which has the same name but several different forms.

For example: we can overload the constructor for the Date class:

Default Date d;
Initializing Date d(9,22,20);
Copy Date d1(d);
Other Date d(“Sept”,22,2020);
Object Oriented Programming 04: Operator Overloading 12

Operator Overloading

The operator “+” also has different semantics depending on the type of its “arguments”
datatype operator + (datatype) { … }
Example

int i, j;
double d, e;
Second parameter (can be native data
type or user defined data type)
i + j; //add two int
i + d; //add an int and a double
Remember operator+ is a function, and it will be
called with the help of any object, thus the first
parameter is the calling object
return parameter
a = b + c;
(can be native data type or user defined data type)
Object Oriented Programming 04: Operator Overloading 13

datatype operator+ (datatype) { }


}
Example 2:
Example 1:

class myClass {
class myClass { int operator+ ( myClass &a ); }
int operator+ ( int );
} int main ( ) {
int a;
int main ( ) { myClass object1, object2;
int a, b; a = object1 + object2;
myClass object; }
a = object + b;
Object Oriented Programming 04: Operator Overloading 14

datatype operator+ (datatype) { }


class myClass {
Example 3:
myClass operator+ ( int ); myClass operator+ ( myClass &a ); }
}
int main ( ) {
int main ( ) {
int a = 5; myClass object1, object2, object3; object3 = object1
myClass object1, object2; + object2;
object2 = object1 + a; }
}
Example 4:

class myClass {
Object Oriented Programming
15
04-02
Implementing Overloaded Operators
04 Operator Overloading
Operators
Object Oriented Programming

Implementing Overloaded
The compiler uses the types of arguments to
choose the appropriate overloading.
s1 + s2; // float+
04: Operator Overloading 16
Object Oriented Programming
int v1, v2;
Example: Employee Class and
v1 + v2; // int +
Objects
04: Operator Overloading 17
float s1, s2;
double operator+ (Employee& emp); double getSalary( )
{ return salary; }
class Employee {
private: };
//function notation
int idNum; double Employee::addTwo(Employee& emp) {
double salary; double total;
total = this->salary + emp.getSalary();
public: return total;
Employee(int id, double salary); }
double addTwo (Employee& emp); //operator overloading notation
double Employee::operator+(Employee& emp) { }
double total;
total = this->salary + emp.getSalary();
return total; // these three statements do the same thing
double sum; Clerk.operator+(Driver); sum = Clerk + // and is easy to remember because it is
Employee Clerk (111, 10000), Driver (222, Driver; consistent // with how the + operator works for
6000); everything else
// the syntax for the last one is the most natural
sum = Clerk.addTwo(Driver); sum =
Object Oriented Programming 18

Multiple Operators
void main( ) {
Often, you may need to reference an operator more Employee Clerk(115, 20000.00);
than once in an expression: Employee Driver(256, 15500.55);
Employee Secretary(567, 34200.00);
double sum;
Example: total = a + b + c;
sum = Clerk + Driver + Secretary;
But this can cause big problems
when operator overloading is involved cout << “Sum is “ << sum;
04: Operator Overloading }
Operator + is left to right associative, so Clerk and Driver are added. The result is a double.
Now that double is on the left and an Employee is on the right (i.e., Secretary)
BUT THE Operator + is only defined for arguments of type Employee, not for double

But the Problem Gets Worse …


although we could overload an operator to work like this: sum = Secretary + num; We cannot overload (with
member function) one like this: sum = num + Secretary; // why not?
Object Oriented Programming
double salary;
The Solution public:

We cannot overload + for a double (a native type) Employee(int id, double salary);
Real solution is to make sure that your operator+ function Employee operator+ (Employee& emp);
never returns a double (or any other native type).
double getSalary( ) { return salary; }
An operator to add Employees should return an Employee
};
04: Operator Overloading
19
class Employee {
private:
double Employee::operator+(Employee& emp) {
int idNum;
Employee total(999,0); // dummy values Employee Secretary(567, 34200.00);
total.salary = salary + emp.getSalary( ); Employee sum(0, 0.0);
return (total);
} sum = Clerk + Driver + Secretary;

void main( ) { }
Employee Clerk(115, 20000.00);
Employee Driver(256, 15500.55);
Object Oriented Programming
20
04-03
Invoking Objects
04 Operator Overloading
Object Oriented Programming explicit argument,
Invoking Objects 04: Operator Overloading 21

If the operator is binary but there is only one

the ‘invoking instance’ is assumed to be the one on the left-hand side of the expression.

class Date {
public: // member functions
Date operator=(Date& d);
};

int main (void) {


s1 = s2; // instead of s1.operator=(s2);
}
Overloading Function
Object Oriented Programming

Non-member Operator 04: Operator Overloading 22

int getX( ) { return x; }


//Setter Function
class MyClass {
void setX( int x ) { this->x = x; }
private:
int x; };
myClass operator+(myClass &a, myClass &b) {
public:
myClass temp;
myClass(int x = 0) { this->x = x; }
temp.setX( a.getX( ) + b,getX( ) );
//Getter Function
return temp;
} object1,setX(10);
object3 = object1 + object2;

void main( ) { cout<< object3.getX( );

myClass object1, object2, object3; }

object1,setX(10);
Object Oriented Programming member-wise copy of the data members.

Assignment Operator = However, there is a problem with implicitly overloaded


operator…
04: Operator Overloading 23
Operator= is overloaded implicitly for every class, so they can
be used for each class objects. Operator= performs
void setValue( int i ) { *ptr = i; }
void print( ) { cout<<*ptr << endl; }
};

//A Class without user defined


assignment operator
void main( ) { Test t1(5) Test t2;
class Test {
t2 = t1;
private:
t1.setValue(10) t2.print( ); return 0;
int *ptr;
}
public:
Test(int i = 0) { ptr = new int( i ) }
Object Oriented Programming
operator > for the comparison operator ‘>’
Overloading > Operator
bool Employee::operator>(Employee& e) {
Set the name of the function with the operator's
name operator + for the addition operator ‘+’ return(seniority > e.seniority);
}
if (emp1 > emp2)
04: Operator Overloading 24
called from the program like this:
Object Oriented Programming
25

04-04
Overloading ++ and --
04 Operator Overloading
Object Oriented Programming
or in the form of postfix ( i++ ) after an object
Overloading ++ and -- But in both cases, the calling object will be i.
04: Operator Overloading 26
Although, the syntax of defining prototype: Object Oriented Programming

datatype operator+ (datatype) i++ and ++i ?


Prefix makes the change, and then it processes the
However, for some operators, there is little bit
variable Postfix processes the variable, then it makes
change in the above syntax: ++, -- operators
the change.
>>, << operators
& and [ ] operators
i = 1;

Operator ++ and -- are different to other j = ++i;


operators of C++. We can call them:
either in the form of prefix ( ++i ) before an object // i is 2, j is 2
04: Operator Overloading
27
int numSold;
public:
Inventory(int stkNum, int sold);
void operator++ ( );
};

i = 1; void Inventory::operator++( ) { numSold++;


}
j = i++; 04: Operator Overloading
28

// i is 2, j is 1
Object Oriented Programming int main( ) {

Overloaded ++
Inventory someItem(789, 84);
//the stockNum is 789
//the numSold is 84
class Inventory {
private: ++someItem;

int stockNum; Inventory Item2 = ++someItem;


//will this instruction work }
04: Operator Overloading
29
}
Object Oriented Programming

Overloaded ++ int main( ) {


Inventory someItem(789, 84);
class Inventory { //the stockNum is 789
//the numSold is 84
private:
int stockNum; ++someItem;
int numSold;
Inventory Item2 = ++someItem;
public: //now it will work
Inventory(int stkNum, int sold);
}
Inventory& operator++ ( ); Object Oriented Programming

};
Using ++ Prefix Notation
Inventory& Inventory::operator++( ) { Inventory *object = new
class Inventory {
Inventory(0,0) numSold++;
object -> numSold = numSold; return (*object); private:
int stockNum; int numSold; Inventory temp(999, numSold);
return temp;
public: }
Inventory(int stkNum, int sold) {
this -> stockNum = stkNum; int main( ) {
Inventory v(55, 11);
this -> numSold = sold; Inventory v2(56, 0);
} v2.Display( );
v2 = ++v;
Inventory operator++ ( );
v2.Display( );
void Display( ) { ++v2;
cout<<“Item Number: ”<<stockNum; v2.Display( );
return 0;
cout<<“ sold “<<numSold<<“ times.”<<endl;
}

Postfix ++
}
Object Oriented Programming
};
04: Operator Overloading
30
class Inventory {
private:
Inventory Inventory::operator++( ) { int stockNum;
numSold++; 04: Operator Overloading
31
Inventory *object = new Inventory(0,0)
numSold++;
object -> numSold = numSold;
Inventory& Inventory::operator++( ) { //prefix
(*object); }
int numSold; public:
return Dummy Argument

Postfix and Prefix ++


Inventory(int stkNum, int sold);
Inventory& operator++ ( ); class Inventory {

Inventory& operator++ ( int ); private:


int stockNum; int numSold;
};
Inventory& Inventory::operator++( int ) {//postfix public:
Inventory *object = new Inventory(0,0) object -> Inventory(int stkNum, int sold) {
numSold = numSold;
numSold++; this -> stockNum = stkNum;
return (*object); this -> numSold = sold;
04: Operator Overloading
} 32
Object Oriented Programming
return (*object);
}
Inventory& Inventory::operator++( ) { //prefix
Inventory *object = new Inventory(0,0) Inventory& Inventory::operator++( int ) { //postfix
numSold++; Inventory *object = new Inventory(0,0)
object -> numSold = numSold;
} Inventory v(55, 11); Inventory v2 = ++v1;
}
}; Inventory v3 = v1++; v1.Display( );
Inventory operator++ ( ); v2.Display( );
object -> numSold = numSold;
void Display( ) { numSold++; v3.Display( );
return (*object); return 0;
cout<<“Item Number: ”<<stockNum; }
}
cout<<“ sold “<<numSold<<“ times.”<<endl;
int main( ) {
Object Oriented Programming
33
04-05
Overloading == and [ ]
04 Operator Overloading
Object Oriented Programming

Assignment Operator =
class Employee {
private:
int idNum;
double salary;
public: Employee emp2;
Employee ( ) { idNum = 0, salary = 0.0; } void setValues (int a, emp2 = 44.6; // emp2 is calling object
int b); }
Object Oriented Programming
void operator= (double );
}; Assignment Operator =
void Employee::setValues ( int idN , double sal ) { salary = sal; class Employee {
idNum = idN; private:
} int idNum;
double salary;
void Employee::operator = (double sal) { salary = sal; public:
} Employee ( ) { idNum = 0, salary = 0.0; } void setValues (int a,
04: Operator Overloading int b);
34
void operator= ( Employee &emp );
};
int main( ) {
Employee emp1; void Employee::setValues ( int idN , double sal ) { salary = sal;
emp1.setValues(10,33.5); idNum = idN;
}
double salary;
void Employee::operator = (Employee &emp) { salary = public:
emp.salary; Employee ( ) { idNum = 0, salary = 0.0; } void setValues (int a,
} int b);
04: Operator Overloading
35
bool operator== ( Employee &emp );
};

int main( ) { void Employee::setValues ( int idN , double sal ) { salary = sal;
Employee emp1; idNum = idN;
emp1.setValues(10,33.5); }

Employee emp2; bool Employee::operator == (Employee &emp) { return (salary


emp2 = emp1; // emp2 is calling object == emp.salary);
} }
Object Oriented Programming 04: Operator Overloading

Assignment Operator ==
36

class Employee { int main( ) {


private: Employee emp1;
int idNum; emp1.setValues(10,33.5);
cout <<“objects do not have equal value”;
Employee emp2;
emp2.setValues(10,33.1); }
Object Oriented Programming
if ( emp2 == emp1 )
cout <<“Both objects have equal value”; Subscript Operator [ ]
04: Operator Overloading 37
else

With the help of [ ] operator, we can define array style syntax for accessing or assigning individual
elements of classes

Student semesterGPA;
semesterGPA[ 0 ] = 3.5;
semesterGPA[ 1 ] = 3.3;
Object Oriented Programming

Subscript Operator [ ]
class Student{
private:
double gpa[8];
public: semesterGPA[0] = 3.7;
Student ( ) {
gpa[0]=3.5; gpa[1]=3.2; gpa[2]=4; gpa[3]=3.3; double gpa = semesterGPA[4];
gpa[4]=3.8; gpa[5]=3.6; gpa[6]=3.5; gpa[7]=3.8;
}
}
double& operator[ ] ( int Index ); How the statement executes?
}; semesterGPA[0]=3.7;

double & Students::operator [ ] (int Index) { The [ ] has highest priority than the assignment
return gpa[Index]; operator, therefore semesterGPA[0] is processed
} first.
04: Operator Overloading
38
semesterGPA[0] calls operator [ ],
which then return a reference of semesterGPA.gpa[0].

int main( ) {
Student semesterGPA;
Object Oriented Programming
39
04-06
Overloading From Native Data Types
04 Operator Overloading
from Native Data Types
Object Oriented Programming

Calling an Overloaded Operator 04: Operator Overloading 40


Previously, we were calling an overloaded operator of a class only with the help of its
object Point a, b, c;
a = b + c; // where + is overloaded in Point class

But, Can we call an overloaded operator of a class from the variables of native data
types? int variable;
Point object;
variable = variable + object;

In above example, it seems that we need to overload + operator for int (native-data
type). But in operator overloading we can't change the functionality of int data type

Calling an Overloaded Operator


Object Oriented Programming
from Native Data Types Friend Function: A Friend function does not need
an object of a class for its calling.
04: Operator Overloading 41
Friend functions can help us in solving this
problem.

Thus, with a simple trick we can set parameter1 of an overloaded object to native data type
and parameter2 to class object.

Friend Functions:
can be given special grant to access private and protected members. A friend function can
be: a) method of another class
b) global function
Friends should be used only for limited purpose, too many functions declared as friends with
protected or private data access, lessens the value of encapsulation
Object Oriented Programming
first parameter of function. friend datatype
Calling an Overloaded Operator
from Native Data Types
operator+ (datatype, datatype)
For Friend Function the syntax is changed,
the first operator is moved from calling object to
04: Operator Overloading 42
(can be native data type
or user defined data
type)
First parameter
(can be native data type
or user defined data
type)
Second parameter
(can be native data type
or user defined data
type)

return parameter
Object Oriented Programming

Example
class Student{
private:
float m_dX, m_dY, m_dZ;
04: Operator Overloading
public: 43
Point(float dX, float dY, float dZ) {
m_dX = dX;
m_dY = dY; int main( ) {
m_dZ = dZ; float variable = 5.6;
} Point cPoint ( 2, 9.8, 3.3 );
friend float operator+ (float var1, Point &p); }; float returnVar;
returnVar = variable + cPoint;
friend float operator+ (float var1, Point &p) { return ( var1 + cout << returnVar; // 7.6
p.m_dX ); return 0;
} }
Object Oriented Programming
44
04-07
Overloading << and >>
04 Operator Overloading
and <<
Object Oriented Programming

Overloading iostream Operators >>


We can use friend function for overloading
iostream operators ( >> or << ). cin >> p;
cout << p; //where cin and cout are object of iostream class
04: Operator Overloading 45
Usually iostream operators ( >> or << ) are not
called from an object of the class Point p;

We can define the prototype of iostream operators ( >> and << ) with the help of Friend function,
and then we do not need any object of a class for their calling.
Object Oriented Programming return out;
Example }
04: Operator Overloading
46
class Student{
private:
float m_dX, m_dY, m_dZ; friend ostream& operator<< (istream &in, Point &cPoint) {
public: in >> cPoint.m_dX;
Point(float dX, float dY, float dZ) { in >> cPoint.m_dY;
m_dX = dX; in >> cPoint.m_dZ;
m_dY = dY; return in;
m_dZ = dZ; }
}
friend ostream& operator<< (ostream &out, Point int main( ) {
&cPoint); friend istream& operator>> (istream &in, Point cout << "Enter a point: " << endl;
&cPoint); }; Point cPoint;
cin >> cPoint;
friend ostream& operator<< (ostream &out, Point &cPoint) {
cout << "You entered: " << cPoint << endl; }
out << "(" << cPoint.m_dX << ", " Object Oriented Programming
<<cPoint.m_dY << ", " << cPoint.m_dZ <<")";
Overloading iostream Operators >>
cin >> cPoint; // cin is first parameter and cPoint is second
parameter

and << Is above statement (cin >> cPoint) returning anything?


But what is the advantage of returning references of
iostream objects friend ostream& operator<< (ostream It is returning reference of iostream object,
&out, Point &cPoint); thus, in above statement the cin reference is
friend istream& operator>> (istream &in, Point &cPoint); returned that can be further used for Point cPoint1,
cPoint2;
To understand above, let look on the first and cin >> cPoint1 >> cPoint2;
04: Operator Overloading 47
second parameters in case of >> and << Point cPoint;
In above statement (cin >> cPoint1) returns a reference of cin which is further used for ( cin >> cPoint2)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy