0% found this document useful (0 votes)
25 views

Object Oriented Programming (CS2133)

This document discusses operator overloading in C++. It begins by listing the main topics that will be covered, including overloading unary, binary, assignment, comparison, subscript, and stream insertion/extraction operators. It then explains the basics of operator overloading, including how operators can be overloaded by defining special member functions. The document provides examples of overloading various operators like unary, binary, assignment, and subscript operators. It also discusses issues like operator precedence and return values when overloading operators.

Uploaded by

REBEL USMAN
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Object Oriented Programming (CS2133)

This document discusses operator overloading in C++. It begins by listing the main topics that will be covered, including overloading unary, binary, assignment, comparison, subscript, and stream insertion/extraction operators. It then explains the basics of operator overloading, including how operators can be overloaded by defining special member functions. The document provides examples of overloading various operators like unary, binary, assignment, and subscript operators. It also discusses issues like operator precedence and return values when overloading operators.

Uploaded by

REBEL USMAN
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 33

Object Oriented Programming

(CS2133)
By
Dr. Muhammad Azhar Iqbal

Department of Computer Science,


Mohammad Ali Jinnah University, Islamabad
Fall Semester, 2013
Operator Overloading
Operator Overloading
 Fundamentals of Operator Overloading
 To know how to overload the unary operators prefix and
postfix ++ and -- operators
 To know how to overload the binary operators
 To know how to overload the assignment operators
 To know how to overload the comparison == operators
 To know how to overload the array subscript operator []
 To know how to overload the stream insertion and
extraction operators << and >>
 To define operator functions to perform object conversion
 To overload the = operator to perform a deep copy
Operator Overloading

 The method of defining additional meanings for


operators is known as operator overloading
 Operator overloading enables an operator to perform
different operations depending upon the type operands
 The basic operators i.e. +, -, *, / normally works with basic
types i.e. double, float, int, long.
 These basic operators have been already defined in C++
language for primitive data types
 So how can these operators can be applied to user-defined
data types
Operator Overloading
 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


How to Overload an Operator

 An operator can be overloaded by declaring a


special member function in the class

 Generally, the name of the member function is


operator that is preceded or followed by operator
symbol e.g. Operator+, Operator++, ++Operator
etc.
Syntax to Overload an Operator

returnType operator opsymbol(parameters){ }


  

any type keyword operator symbol function body

 Return type may be whatever the operator returns

 Operator symbol may be any overloadable operator

Example:

void operator+ (parameters){ }


   
any type keyword operator symbol function body
Overloadable Operators

+ - * / % ^ & | ~ ! =
< > += -= *= /= %= ^= &= |= <<
>> >>= <<= == != <= >= && || ++ --
->* , -> [] () new delete
Operators That Cannot Be Overloaded

?: . .* ::
Overloading (Prefix) Unary Operators

class Counter
{ void main() {
private: Counter c1, c2;
int count;
public: cout<<c1.getCount();
Counter() : count(0) cout<<c2.getCount();
{ } ++c1;
int getCount( ) ++c2;
{ return count; } ++c2;
void operator++( )
{ ++count; } cout<<c1.getCount();
}; cout<<c2.getCount();
}
Operators Return Value
class Counter
{
private: void main() {
int count; Counter c1, c2;
public:
Counter() : count(0) cout<<c1.getCount();
{ } cout<<c2.getCount();
int getCount( ) ++c1;
{ return count; } c2 = ++c1;
Counter operator++( )
{
++count; cout<<c1.getCount();
Counter temp; cout<<c2.getCount();
temp.count = count; }
return temp;
}
};
Operators Return Value – Nameless Temporary Objects
More convenient way to return nameless (anonymous) temporary objects
from functions and overloaded operators.
class Counter
{ void main() {
private: Counter c1, c2;
int count;
public: cout<<c1.getCount();
Counter() : count(0) cout<<c2.getCount();
{ }
Counter(int c):count(c) ++c1;
{ } c2 = ++c1;
int getCount( )
{ return count; } cout<<c1.getCount();
Counter operator++( ) cout<<c2.getCount();
{ }
++count;
return Counter(count);
}
};
Overloading (Postfix) Unary Operators
class Counter
{ void main() {
private: Counter c1, c2;
int count;
public: cout<<c1.getCount();
Counter() : count(0) cout<<c2.getCount();
{ }
Counter(int c):count(c) ++c1;
{ } c2 = ++c1;
int getCount( )
{ return count; } cout<<c1.getCount();
Counter operator++( ) cout<<c2.getCount();
{
++count; c2 = c1++;
return Counter(count);
} cout<<c1.getCount();
Counter operator++(int) cout<<c2.getCount();
{
return Counter(count++); }
}
};
Overloading Binary Operators (Arithmetic Operators)

class Counter
{ void main() {
private: Counter c1(10, 20);
int count1, count2; Counter c2(5,10);
public: Counter c3;
Counter() : count1(0), count2(0)
{ } c1.showCount();
Counter(int n1, int n2) : count1(n1), count2(n2) c2.showCount();
{ } c3.showCount();
void showCount( )
{ cout<<count1<<“ ”<<count2; } c3 = c1 + c2;
Counter operator + (Counter c)
{ c1.showCount();
int temp1 = count1 + c.count1; c2.showCount();
int temp2 = count2 + c.count2; c3.showCount();
return Counter(temp1, temp2);
} }
};
Overloading Binary Operators
(Arithmetic Assignment Operators)
class Counter
{ void main() {
private: Counter c1(10, 20);
int count1, count2; Counter c2(5,10);
public:
Counter() : count1(0), count2(0) c1.showCount();
{ } c2.showCount();
Counter(int n1, int n2) : count1(n1), count2(n2)
{ } c1 += c2;
void showCount( ) // c1 = c1 + c2;
{ cout<<count1<<“ ”<<count2; }
void operator += (Counter c) c1.showCount();
{ c2.showCount();
count1 += c.count1;
count2 += c.count2; }

}
};
Precedence and Associativity

C++ defines the operator precedence and


associativity. You cannot change the operator
precedence and associativity by overloading.
Overloading the [] Operator
#include <iostream> int main()
const int SIZE = 10; {
safearay A;
class safearay{
private: cout << "Value of A[2] : " << A[2] <<endl;
int arr[SIZE]; cout << "Value of A[5] : " << A[5]<<endl;
public: cout << "Value of A[12] : " << A[12]<<endl;
safearay(){
register int i; return 0;
for(i = 0; i < SIZE; i++) }
{ arr[i] = i; }
} /* must be with & because sometimes it is
int& operator[](int i) { used on left side of assignment operator */
if( i > SIZE )
{
cout << "Index out of bounds\n”;
// return first element.
return arr[0];
}
return arr[i];
}
};
Overloading the [] Operator
#include <iostream> int main()
const int SIZE = 10; {
safearay A;
class safearay{ A[0] = 15; //Its Ok here
private: cout << "Value of A[2] : " << A[2] <<endl;
int arr[SIZE]; cout << "Value of A[5] : " << A[5]<<endl;
public: cout << "Value of A[12] : " << A[12]<<endl;
safearay(){
register int i; return 0;
for(i = 0; i < SIZE; i++) }
{ arr[i] = i; }
} /* must be with & because sometimes it is
int& operator[](int i) { used on left side of assignment operator */
if( i > SIZE )
{
cout << "Index out of bounds\n";
// return first element.
return arr[0];
}
return arr[i];
}
};
Overloading the [] Operator
#include <iostream> int main()
const int SIZE = 10; {
safearay A;
class safearay{ // A[0] = 15; wrong here
private: cout << "Value of A[2] : " << A[2] <<endl;
int arr[SIZE]; cout << "Value of A[5] : " << A[5]<<endl;
public: cout << "Value of A[12] : " << A[12]<<endl;
safearay(){
register int i; return 0;
for(i = 0; i < SIZE; i++) }
{ arr[i] = i; }
} /* must be with & because sometimes it is
int operator[](int i) { used on left side of assignment operator */
if( i > SIZE )
{
cout << "Index out of bounds" <<endl;
// return first element.
return arr[0];
}
return arr[i];
}
};
Overloading the << and >> Operators

C++ allows you to overload the stream insertion operator (<<) for
sending an object to cout and overload the stream extraction
operator (>>) for reading values from cin. Overloading these two
operators is different from other operators. Since the first
parameter of the << (>>) operator is an instance of ostream
(istream), these two operators are defined in the ostream and
istream classes.
Overloading the << and >> Operators…

Important things to take care of before starting implementation for


overloading an operator:

The first thing is to notice the type of the operator i.e. whether the
operator is binary or unary. The binary operator has two operands
while unary operators takes one. The number of operands cannot be
changed while overloading it.

Secondly, the programmer has to take care of, what an operator is


returning back. For example, in case of addition, it returns back the
result of addition. So the cascading statement like a+b+c; can be
executed successfully. In this case, at first, b+c is executed. The result
of this operation is returned by operator +, to add it in the variable a.
so in actual, the operation is carried out as: a+(b+c)
Overloading the << and >> Operators…
 There are two ways of overloading operators either as a class
members or non-member.
 Insertion (<<) and extraction (>>) operators cannot be overloaded
as members.
 The reason is obvious as the object on the left side of the operator
is not class member. (cin and cout objects will remain intact for
our overloaded insertion and extraction operators. Therefore,
overloaded operators cannot be member operators).
 So, we can overload << and >> operators as non-members.
 Declare the operators as the friend of the class to access the
private members directly.
 We should declare friends of our classes and not those of library
class e.g. we should not declare a function as friend of istream or
ostream class.
Overloading the << and >> Operators…

 The object on the left of our operator will be a stream object


like cin, cout and on the right will be the object of our class.

 We should be clear about the return type of the overloaded


operator as the operator function has to support the
cascading operations. For example, in case of stream
insertion operator (<<), the operator function returns a
reference to ostream to support cascading operations.
Example

<< and >> operators


 Already overloaded to process each built-in type
and pointers and strings.
 Can also process a user-defined class.
 Overload using global, friend functions

Example program
 Class Date
 Class Matrix
 Class Phone
Overloading the >> and << Operator – Example 1

class Date
{
public:
Date( )
{
cout << "\n Parameterless constructor called ...";
month = day = year = 0;
}
~Date ( )
{
cout << "\n Destructor called ...";
}
friend ostream & operator << ( ostream & os, Date &d );
friend istream & operator >> ( istream & is, Date &d );
private:
int month, day, year;
};
Overloading the >> and << Operator – Example 1
ostream & operator << ( ostream & os, Date &d )
{
os << d.day << "." << d.month << "." << d.year; 
return os;
}
istream & operator >> ( istream & is, Date& d )
{
cout << "\n\n Enter day of the date: ";
is >> d.day;
cout << " Enter month of the date: ";
is >> d.month;
cout << " Enter year of the date: ";
is >> d.year;
return is;
}
main(void) {
Date date1, date2;
cout << "\n\n Enter two dates";
cin >> date1 >> date2;
cout << "\n Entered date1 is: " << date1 << "\n Entered date2 is: " << date2;
}
Overloading the >> and << Operator – Example 2

class Matrix{
private:
float Element[3][3];
int nRows, nCols;
public:
Matrix(int rows = 0, int cols = 0)
{
nRows = rows;
nCols = cols;
}

friend ostream& operator<<(ostream &output, Matrix &m);


friend istream& operator>>(istream &input, Matrix &m);
};
Overloading the >> and << Operator – Example 2
istream& operator >>(istream& input, Matrix &m){
for(int i=0; i<m.nRows; i++)
{ for(int j=0; j<m.nCols; j++)
input>>m.Element[i][j];
}
return input;
}
ostream& operator<<(ostream &output, Matrix &m){
for(int i=0; i<m.nRows; i++)
{ for(int j=0; j<m.nCols; j++)
output<<m.Element[i][j]<<"\t";

output<<endl;
}
return output;
}
void main(){
Matrix matrix(3,3);
cout<<"Enter 9 values to initialize Matrix \n";
cin>>matrix;
cout<<"output in Matrix form is \n";
cout<<matrix;
}
Overloading the >> and << Operator – Example 3

#include <iostream>
using std::ostream;
using std::istream;
#include <string>
using std::string;

class PhoneNumber
{
private:
string areaCode; // 3-digit area code
string exchange; // 3-digit exchange
string line; // 4-digit line

friend ostream &operator<<( ostream &, const PhoneNumber & );


friend istream &operator>>( istream &, PhoneNumber & );
};
Overloading the >> and << Operator – Example 3

#include <iomanip>
using std::setw;

#include "PhoneNumber.h"

// overloaded stream insertion operator; cannot be


// a member function if we would like to invoke it with
// cout << somePhoneNumber;

ostream &operator<<( ostream &output, const PhoneNumber &number )


{

output << "(" << number.areaCode << ") " << number.exchange << "-" << number.line;

return output; // enables cout << a << b << c;

} // end function operator<<


Overloading the >> and << Operator – Example 3

// overloaded stream extraction operator; cannot be


// a member function if we would like to invoke it with
// cin >> somePhoneNumber;

istream &operator>>( istream &input, PhoneNumber &number )


{

input.ignore(); // skip (
input >> setw( 3 ) >> number.areaCode; // input area code
input.ignore( 2 ); // skip ) and space
input >> setw( 3 ) >> number.exchange; // input exchange
input.ignore(); // skip dash (-)
input >> setw( 4 ) >> number.line; // input line
return input; // enables cin >> a >> b >> c;

} // end function operator>>


Overloading the >> and << Operator – Example 3
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include "PhoneNumber.h"

int main()
{
PhoneNumber phone; // create object phone
cout << "Enter phone number in the form (123) 456-7890:" << endl;

// cin >> phone invokes operator>> by implicitly issuing the global function call operator>>( cin, phone )

cin >> phone;


cout << "The phone number entered was: ";

// cout << phone invokes operator<< by implicitly issuing the global function call operator<<( cout, phone )

cout << phone << endl;

return 0;
} // end main
Exercise

 Write a class Array that contains an array of integers as data


member. The class contains the following member functions:

 A no-arg constructor that initializes the array elements to -1.

 A setter(mutator) function to change the values in the array.

 A display function to display the values of the array.

 Overload == operator to compare the values of two objects.


This overloaded operator function returns 1 if all values of
both objects are same and returns 0 otherwise.

You might also like