CSC-210: Object Oriented Programming
Operator Overloading
Lecture 09
By: Ms. Zupash Awais
Bahria University Lahore Campus
▪ >> used with cin
▪ Extraction operator
Istream and ▪ Used for input
ostream ▪ << used with cout
operators ▪ Insertion operator
▪ Used for output
▪ cout is an object of ostream class and cin is an object of
istream class
Things to ▪ These operators must be overloaded as a global function.
Understand And if we want to allow them to access private data
members of the class, we must make them friend.
▪ In operator overloading, if an operator is overloaded as a
member, then it must be a member of the object on the left
side of the operator.
▪ For example, consider the statement “ob1 + ob2” (let ob1
and ob2 be objects of two different classes). To make this
statement compile, we must overload ‘+’ in a class of ‘ob1’
Why these or make ‘+’ a global function.
operators must be ▪ The operators ‘<<‘ and ‘>>’ are called like ‘cout << ob1’
overloaded as and ‘cin >> ob1’. So, if we want to make them a member
method, then they must be made members of ostream and
global? istream classes, which is not a good option most of the
time.
▪ Therefore, these operators are overloaded as global
functions with two parameters, cout and object of user-
defined class.
#include<iostream>
using namespace std;
class Stream
{
int i, j;
public:
Stream():i(0), j(0){}
friend ostream& operator << (ostream& out, const Stream& s);
friend istream& operator >> (istream& in, Stream& s);
};
ostream& operator << (ostream& out, const Stream& s)
{
out << s.i << " " << s.j << endl;
return out;
}
istream& operator >> (istream& in, Stream& s)
{
cout << "Enter value of i ";
in >> s.i;
cout << "Enter value of j ";
in >> s.j;
return in;
}
int main()
{
Stream obj;
cin >> obj;
cout << obj;
}