OOP04 Operator Overloading
OOP04 Operator Overloading
Operator Overloading
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
Operators)
type int / type int type long / type long
9/5 9L / 5L
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
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
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
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
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
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
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);
};
object1,setX(10);
Object Oriented Programming member-wise copy of the data members.
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
// 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;
};
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
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); }
Assignment Operator ==
36
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
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
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
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