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

Operatoroverloading ch5

The document provides a comprehensive overview of operator overloading in C++, detailing how to overload various operators including binary, unary, and relational operators. It explains the syntax for overloading operators, the restrictions involved, and the use of friend functions to access private data members of classes. Additionally, it includes examples of overloading operators in user-defined classes and highlights the importance of using friend functions in certain scenarios.

Uploaded by

vraj820085
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views64 pages

Operatoroverloading ch5

The document provides a comprehensive overview of operator overloading in C++, detailing how to overload various operators including binary, unary, and relational operators. It explains the syntax for overloading operators, the restrictions involved, and the use of friend functions to access private data members of classes. Additionally, it includes examples of overloading operators in user-defined classes and highlights the importance of using friend functions in certain scenarios.

Uploaded by

vraj820085
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64

Operator overloading

• It is just a type of function overloading


• When operator is used to perform operation on other than standard data
type it is known as overloading
• Operator is always overloaded relative to a user defined type such as a class
• When we overload operator it is member function.
• Operator function cannot have default arguments

general form
return type class name::operator operator name(agr_list)
{
// operation to be performed
}
• Two restrictions
• 1. precedence of the operator can note be changed
• 2. the number of operands that an operator takes can not be altered
Following operators can not be overloaded
. :: .*(Pointer to member operator) ?:(Ternary or conditional
operator) #, sizeof
Overloading binary operators e.g + operator
class coord
{
int x;
int y;
public:
coord()
{
x=0;
y=0;
}
coord(int a,int b)
{
x=a;
y=b;
}
coord operator +(coord);
coord operator +(int);
void display(){ cout<<"xcord"<<x<<"ycord"<<y<<endl;} };
coord coord::operator +(coord o)
{
coord temp;
temp.x=x+o.x;
temp.y=y+o.y;
return temp;
}
coord coord::operator +(int i)
{
coord temp;
temp.x=x+I;
temp.y=y+I;
return temp;}
int main()
{
coord c1(2,3),c2(4,5);
coord c3,c4;
c3=c1 + c2;
c4=c3+5;
c3.display();
c4.display();
return 0}
• You can also write
• (c1+c2).display();
• c4=c1+c2+c3;
• c3=c1.operator +(c2)
Overload – and = operator
Note : when a binary operator is overloaded, the left operand is
passed implicitly to the function and the right operand is passed as an
argument
c3=c1-c2 order is important i.e. subtract operand on the right from the
operand on the left
• coord coord::operator = (coord ob)
• {
• x=ob.x;
• y=ob.y;
• return *this;
• }
• c2=c1;
• c3=c2=c1;
• There is no rule that required an overloaded assignment function to
return the object that receives the assignment. However if you want
the overloaded = to behave relative to its class the way it does for the
built-in types, it must return *this
• By default assignment is already overloaded then why to overlod =
operator
• Because it do bitwise copy
class samp
{
char *p;
int len;
public:
samp()
{
p='\0';}
samp(char *s)
{
int l;
l=strlen(s);
p=new char[l+1];
strcpy(p,s);
len=l; }
samp &operator=(samp &s1);
void display(){ cout<<p<<endl;}
~samp(){cout<<"destructor\n";delete [] p;}
samp & samp::operator = (samp &ob)
{

p=new char[ob.len+1];
len=ob.len;
strcpy(p,ob.p);
return *this;
}
int main()
{
clrscr();
samp s1("hello");
samp s2("how");
samp s3("fine");
s1.display();
s2.display();
s1=s2;
s1.display();
s2.display();
s2=s3;
s1.display();
s2.display();
s3.display();
return 0;
}
output
Overloading relational and logical operators
• They return integer that indicates true or false. They can return bool
type
class coord
{
int x;
int y;
public:
coord()
{
x=0;
y=0;
}
coord(int a,int b)
{
x=a;
y=b;
}

int operator ==(coord);


int operator&&(coord);
void display(){ cout<<"xcord"<<x<<"ycord"<<y<<endl;}
};
• int coord::operator == (coord ob)
• {
• if(x==ob.x &&y==ob.y)
• return 1;
• return 0;
• }
• int coord::operator &&(coord ob)
• {
• if((x&&ob.x)&&(y&&ob.y))
• return 1;
• return 0;
• }
• int main()
• {
• coord c1(2,3),c2(4,5);
• coord c3,c4;
• if(c1==c2)
• cout<<"equal\n";
• else
• cout<<"not equal\n";

• if(c1&&c2)
• cout<<"true\n" ;
• else
Home work
• Overload < and > operator relative to complex class
Overload unary operator
• The function has no parameter, since there is only one operand. That
is the object that generates call to the operator function
• How to differentiate prefix and postfix
• Write one definition with one dummy parameter
• In case of postfix it invoke definition with dummy parameter and in
case of prefix call definition without parameter
class test
{
int i;
public:
test()
{ i=0;
}
test(int j)
{
i=j;
}
test operator ++();
test operator ++(int);
test operator-();
void display()
{
cout<<i;
}
};
test test :: operator-()
{
i=-i;
return *this;
}
test test::operator ++()
{
test temp; // i++; return *this;
temp.i=++i;

return temp;
}
test test ::operator ++(int p)
{
test temp; // return test(i++);
temp.i=i;
i++;
return temp;
int main()
{
clrscr();
test ob(4),ob1,ob2;
ob1=++ob;
ob2=ob++;
ob1.display();
ob2.display();
ob.display();
ob2=-ob1;
ob1.display();
return 0;}
O v e rlo a d []o p e ra to r

• Operator [] is array subscripting operator


class arraytype
{
int *a;
int len;
public:
arraytype(int size)
{
a=new int[size];
int i;
for(i=0;i<size;i++)
a[i]=i;
}

int operator [](int i)


{
return a[i];
}
};
int main()
{

int n,i;
cout<<"array size\n";
cin>>n;
arraytype ob(n);
for(i=0;i<n;i++)
cout<<ob[i]<<endl;
return 0;
}
• I want to write
• ob[i]=ob[i]+10;
• int &operator [](int i) { return a[i];}
Home work
• Declare a class called animal having private data members name and
speed. Define following functions
• Default constructor for reading data members form keyboard
• Overloaded constructor with two arguments
• Display function
• Overloaded operator =
• Overloaded operator >= to compare speed of two animal objects
Define main to illustrate use of above functions
Home work
• Overload operator + two concate two string object
• s3=s1+s2;
• Do you required copy constructor?
Friend function
• Some times we want a function to access private data member of a class without that function
actually being a member of that class
• Such function is known as friend function
• A friend function is not a member of a class but still has access to its private data members
• A friend function is declared inside the class with a friend keyword preceding as shown
below.
• class className{

• ……

• friend returnType functionName(arg list);


• };
• The function can be defined anywhere in the code file and we need not use the keyword friend
or the scope resolution, operator.
• It can be friend of more than one class
Friend function
• There are some points to remember while implementing friend functions in our program:
• A friend function can be declared in the private or public section of the class.
• It can be called like a normal function without using the object.
• A friend function is not in the scope of the class, of which it is a friend.
• A friend function is not invoked using the class object as it is not in the scope of the class.
• A friend function cannot access the private data members of the class directly. It needs to
make use of a class object and then access the members using the dot operator.
• A friend function can be a global function or a member of another class.
• Cannot have this pointer
• Usually it has the objects as arguments
• It cannot be inherited
Friend function
• It is useful in operator overloading
e.g. c2=2+c1
When you want one function to have access to the private members of
two or more different classes
Operator overloading using friend function
class coord
{
int x;
int y;
public:
coord()
{
x=0; y=0;
}
coord(int a,int b)
{
x=a; y=b;
}
friend coord operator +(coord,coord);
friend coord operator +(int,coord);
friend coord operator +(coord,int);
void display(){ cout<<"xcord"<<x<<"ycord"<<y<<endl;} };
coord operator +(coord o1,coord o2)
{
coord temp;
temp.x=o1.x+o2.x;
temp.y=o1.y+o2.y;
return temp;
}
coord operator + (int a,coord ob)
{
coord temp;
temp.x=ob.x+a;
temp.y=ob.y+a;
return temp;
}
coord operator + (coord ob,int a)
{
coord temp;
temp.x=ob.x+a;
int main()
{
coord c1(2,3),c2(4,5);
coord c3,c4;
c3=c1+c2;
c3.display();
c4=2+c1;

c4.display();
c4=c2+5;
c4.display();

return 0;}
Friend of more than one class
Add objects of two different classes

class ABC; // forward declaration


class XYZ
{
int data;
public:
XYZ(int v)
{
data=v;
}
friend void add(XYZ,ABC);
};
class ABC
{
int data;
public:
ABC(int v)
{
data=v;
}
friend void add(XYZ,ABC);
};

void add(XYZ ob1,ABC ob2)


{
cout<<"sum="<<ob1.data+ob2.data<<endl;
}
int main()
{
XYZ A(3);
ABC B(5);
add(A,B);
return 0;
}
Home work
• Swapping private data of two classes
• Find transpose of matrix using friend function
• Write a program to find maximum of two numbers using friend function,
both the number are member of two different classes
• Write a program to add two objects of class complex using friend function
• Declare two classes’ pr1 and pr2 with appropriate data members. Object
of both classes share printer. Declare a function called inuse() that returns
true when the printer is being used by either and false otherwise. Define
other member functions if required. Define main to show the usage of
above functions.
Swapping private data of two classes

class B;
class A
{ int x;
public:
A(int i){x=i;}
void display(){cout<<“x=“<<x<<endl;}
friend void swap(A&,B&);
};
class B
{
int y;
public:
B(int j){y=j;}
void display(){cout<<“y=“<<y<<endl;}
friend void swap(A&,B&);
};
void swap(A &a,B &b)
{
int temp=a.x;
a.x=b.y;
b.y=temp;}
int main()
{
A o1(5);
B o2(7);
o1.display();
o2.display();
swap(o1,o2);
o1.display();
o2.display();
return 0;}
#include<iostream>
using namespace std;
class pr2;
class pr1
{
int printing;
public:
pr1()
{
printing=0;
}
void set_print(int s)
{
printing=s;
}
friend int inuse(pr1,pr2);
};
class pr2
{
int printing;
public:
pr2()
{
printing=0;
}
void set_print(int s)
{
printing=s;
}
friend int inuse(pr1,pr2);
};

int inuse(pr1 p1,pr2 p2)


{
if(p1.printing==0&&p2.printing==0)
return 0;
return 1;
}
int main()
{
pr1 ob1;
pr2 ob2;
if(inuse(ob1,ob2))
cout<<"printer is in use\n";
else
cout<<"printer is free\n";
ob1.set_print(1);
if(inuse(ob1,ob2))
cout<<"printer is in use\n";
else
cout<<"printer is free\n";
return 0;

}
• Write a program to define class A and B, having two data members a
and b and c and d respectively. first is private and second is public.
define friend function add() to add two private data member, mul() to
multiply two public member and display to display all numbers. Use
constructor to initialize data member
class B;
class A {
private:
int a;

public:
int b;
A()
{ cout<<"enter a and b\n";
cin>>a>>b; }
friend int add(A,B);
friend int mul(A,B);
friend void display(A,B);
};
class B {
private:
int c;

public:
int d;
B(){cout<<"enter c and d\n";
cin>>c>>d;}
friend int add(A,B);
friend int mul(A,B);
friend void display(A,B);
};
int add(A o1,B o2)
{
return(o1.a+ o2.c);
}
int mul(A o1,B o2)
{
return(o1.b*o2.d);
}
void display(A o1,B o2)
{
cout<<"Aprivate"<<o1.a<<endl;
cout<<"Apublic"<<o1.b<<endl;
cout<<"Bprivate"<<o2.c<<endl;
cout<<"Bprivate"<<o2.d<<endl;
cout<<"add"<<add(o1,o2)<<endl;
cout<<"mul"<<mul(o1,o2)<<endl; }
int main()
{
A x;
B y;
display(x,y);
return 0;
}
Member of one class can be friend of another
class
class bus;
class car
Friend function to compare speed of
{
int speed;
bus and car
public:
car(int x)
{
speed=x;
}
void display()
{
cout<<"speed of car"<<speed<<endl;
}
int compare_speed(bus);
};
class bus
{
int speed;
public:
bus(int y)
{
speed=y;}
void display()
{
cout<<"bus speed"<<speed<<endl;}
friend int car::compare_speed(bus);
};
int car::compare_speed(bus ob)
{
if(speed<ob.speed)
return 1;
return 0;
}
int main()
{
car c(20);
bus b(50);
c.display();
b.display();
if(c.compare_speed(b))
cout<<"bus speed is
more than car\n";
else
cout<<"car speed is
more than bus\n";
return 0;}
Overload ++ operator using friend function
class test
{
int i;
public:
test()
{ i=0;
}
test(int j)
{
i=j;
}

friend test operator ++(test &); //prefix


friend test operator ++(test &,int); //postfix

void display()
{
cout<<i;
}};
test operator ++(test &ob)
{

ob.i++;
return ob; //return ++ob.i

}
test operator ++(test &ob,int p)
{
return ob.i++;//return test(ob.i++);
}
int main()
{
clrscr();
test ob(4),ob1,ob2;
ob1=++ob;
ob2=ob++;
ob1.display();
ob2.display();
ob.display();

return 0;
Friend class
• We can also declare all the member function of one class as the friend
functions of another class. In such cases the class is called a friend class
• A friend class can access private members of other class in which it is
declared as friend. It is sometimes useful to allow a particular class to
access private members of other class
class z
{
friend class x; // all member functions of x are friend to z
};
class A {
private:
int a;
public:
A() { a = 0; }
friend class B; // Friend Class
};
class B {
private:
int b;
public:
void showA(A x)
{
// Since B is friend of A, it can access
// private members of A
cout<<b;
cout << "a=" << x.a;
} };
int main()
{
A a;
B b;
b.showA(a);
return 0;
}
Friend class
class Square
{
friend class Rectangle; // declaring Rectangle as friend class
int side;
public:
Square ( int s )
{
side = s;
}
};
class Rectangle
{
int length;
int breadth;
public:
Rectangle(int a=0,int b=0)
{
length=a;
breadth=b;
}
int shape()
{ return length * breadth;
}
int shape( Square a )
{
length = a.side;
breadth = a.side;
return length * breadth;
}
int main()
{
Square square(5);
Rectangle rectangle;
cout<<rectangle.shape(square)<<endl;
Rectangle r(10,20);
cout << r.shape() << endl;
return 0;
}
Friend can not be used
• Assignmnet =
• Functional call ()
• Subscripting []
• Class member access operator ->
• Define class book having data members like title, author, price and no
of pages. Declare title and author as pointer. Use dynamic memory
allocation. Overload > =operator to compare price of two book using
friend function. Do you think you required copy constructor?
class book
{
char *b_name;
char *aut_name;
int price;
int pages;
public:
book()
{
b_name=new char[10];
aut_name=new char[10];
cout<<"enter book anme, author name,price and no of pages"<<endl;
cin>>b_name>>aut_name>>price>>pages;
}
void display()
{
cout<<"book anme, author name,price and no of pages"<<endl;
cout<<b_name<<" "<<aut_name<<" "<<price<<" "<<pages;
}
friend int operator>=(book,book);
book(const book &);
int operator>=(book b1,book b2)
{
if(b1.price>=b2.price)
return 1;
return 0;
}

book::book(const book & b )


{
cout<<"copy const\n";
b_name=new char[strlen(b.b_name)+1];
aut_name=new char[strlen(b.aut_name)+1];
strcpy(b_name,b.b_name);
strcpy(aut_name,b.aut_name);
price=b.price;
pages=b.pages;
int main()
{
clrscr();
book b1,b2;
b1.display();
b2.display();
if(b1>=b2)
cout<<"book1 price is grater or equal\n";
else
cout<<"book2 price is grater\n";

return 0;
}
output

You might also like