Object Oriented Programming (OOP)
------------------------------------------------------
Lecture Topic: Operator Overloading and Friend Function
------------------------------------------------------
Instructor: Muhammad Aizaz Akmal
------------------------------------------------------
Lecture Oultine
0:Recape of previous Lecture
1:Operator Overloading
-What is operator Overloding
-Function Overlaod(function with same name but different parameter list)
void fun(int i);
void fun(string name);
void fun(int i, float j);
void fun(int i, float j);//Error redefination of function
-default operator support on object
asignment operator (=), dot operator (.)
Distance d1(10,2.5);
Distance d2(20,3.9);
Distance d3 = d2 + d1;
int i,j,k;
i=5;
j=10;
k=i+j;
-Operator Overloading is facility that allow the programmar to perform
operator on the object according to provided specification.
-Uniary Operator Overload
-- (prefix,postfix), ++(prefix, postfix)
-How to overlaod operator
returntype operator # (); //# denote any uniary opeator
void operator ++()
{
++inch;
++feet;
}
-How to call overloaded operator;
Distance d1(10,2.3);
++d1;
-Binary Operator Overload
Arithmeti Operator(+,-,*,/,%), Relational Operator (<,>,<=,>=,!=,==)
Logical Operator(&&,||)
returntype operator # (Datatype Obj); //# denote any binary opeator
d3 = d1+d2 // [Link]+(d2)
Distance operator+(Distance tobj)
{
Distance temp;
[Link]= feet + [Link];
[Link]= inch + [Link];
return temp;
}
bool operator==(Distance tobj)
{
if ((feet == [Link]) && (inch == [Link]))
return true;
else
return false;
}
-Subsript Operator Overload([])
returntype& operator[](int index);
int& operator[](int i)
{
if(i>=size)
{
cout<<"index out of bound"<<endl;
return NULL;
}
else
return arr[i];
}
2:Friend Function
- Non member function that allowed to access the data members of class
both public and private after declaring them as a freind in a class.
friend void nonMemDisplay(Distance td);
void nonMemDisplay(Distance td)
{
[Link]=10; //private //error
[Link]();
}
string s1="Hello";
string s2="World";
string s3=s1+s2; //Hello World
s1<s2 //bool
s1==s2 //bool
s1*s2
3:Operator overlaod as non member of class
-Insertion Operator <<
ostream& operator<<(ostream &out, ClassType &obj);
friend ostream& operator<<(ostream &out, Distance &td);
ostream& operator<<(ostream &out, Distance &td)
{
out<<"Distance is: "<<[Link] <<"\'-" <<[Link] <<"\""<<endl;
return out;
}
-Extraction Operator >>
istream& operator>>(istream &in, ClassType &obj);
friend istream& operator>> (istream &in, Distance &td);
istream& operator>>(istream &in, Distance &td)
{
cout<<"Enter the value of feet"
in>>[Link];
cout<<"Enter the value of inch"
in>>[Link];
return in;
}
4:Restriction on Operator Overloading
The operator that can't be overlaod
dot(.), scoperesulation operator (::), sizeof, ternary operator ?:, .*
- overload only existing operator except above mentioned.
- Can't change the predence of operator
- Can't change the associativity of operator.