CSE1002 Operator Overloading CPP
CSE1002 Operator Overloading CPP
Overloading
1
Operator Overloading
• C++ has the ability to provide the operators with a special
meaning for a data type.
2
Operator Overloading
Operator Overloading refers to giving the
normal C++ Operators, such as +,*,<= etc.,
additional meanings when they are applied
to user defined data types.
4
The non-Over loadable
Operators
5
The purpose of using
operator function
To define an additional task to an operator, we must specify what it
means in relation to the class to which the operator is applied.
This is done by Operator function , which describes the task.
Operator functions are either member functions or friend functions.
The overloaded operator must have at least one operand that is of user
defined data type.
• Also the left hand side operand must be an object of the relevant
class.
9
Unary operator overloading
using member functions
-Example
10
Syntax for overloading unary operators
11
Unary operator overloading
using member functions
// unary ++ overloading
#include<iostream.h>
class counter
counter operator ++()
{
private : {
unsigned int count; ++count;
public : counter temp;
counter() temp.count=count;
{ return temp;
count=0; }
}
};
int get_count()
{ return count; } 12
Unary operator overloading
using member functions
void main()
{
counter c1,c2;
cout<<"\n c1 ="<<c1.get_count();
cout<<"\n c2 ="<<c2.get_count();
++c1; OUTPUT :
c2=++c1; C1 = 0
cout<<"\n c1 ="<<c1.get_count(); C2 = 0
cout<<"\n c2 ="<<c2.get_count();
} C1 = 2
C1 = 2
13
Unary operator overloading
using member functions
#include<iostream>
using namespace std;
class Complex
{ private:
int real;
int imag;
public:
Complex(int r, int i) { real = r; imag = i; }
Complex operator ++(int);
Complex &operator ++();
void display() 14
{ cout<<real<<imag<<endl; }
};
Unary operator overloading
using member functions
Complex &Complex::operator ++()
{ real++; imag++;
return *this;}
Complex Complex::operator ++(int i)
{ Complex c1(real, imag);
real++; imag++;
return c1;}
int main()
{ Complex c1(10, 15);
c1++; c1.display();
++c1; c1.display(); 15
return 0;
}
Binary operator overloading
using member functions
- Example
16
Syntax for overloading a binary operator
17
Binary operator overloading
using member functions
#include<iostream.h>
class Distance
{ void get()
private : {
int feet;
cout<<"\n Enter Feet :";
float inches;
cin>>feet;
public :
Distance()
{ cout<<"\n Enter inches :";
feet=0; cin>>inches;
inches=0.0; }
} void show()
{
Distance(int ft,float in)
cout<<feet<<inches<<"\n";
{
}
feet=ft;
inches=in; Distance operator +(Distance);
18
} };
Binary operator overloading
using member functions
void main()
Distance Distance ::operator +(Distance
{
d2)
Distance d1,d3,d4;
{
Distance d2(11,6.25);
int f=feet+d2.feet;
d1.get();
float i=inches+d2.inches;
d3=d1+d2;
d4=d1+d2+d3; return Distance(f,i);
cout<<"\n D1= ";d1.show(); }
cout<<"\n D2= ";d2.show();
OUTPUT :
cout<<"\n D3= ";d3.show();
Enter feet : 5
cout<<"\n D4= ";d4.show(); Enter inches : 4.4
} d1 = 5 4.4
d2 = 11 6.25
d3 = 16 10.65
d4 = 32 21.299999
19
Overloading Arithmetic
Operators
[Additional Examples]
20
Overloading arithmetic operator
#include<iostream.h> void accept()
class operations {
{
cout<<"\n Enter 2 Values";
public :
cin>>a>>b;
int a,b,c,d,e;
operations operator + (operations p) }
{ };
p.c=p.a+p.b; void main()
return p;} {
operations operator - (operations q) operations x;
{ x.accept();
q.d=q.a-q.b; x.c=x.a+x.b;
return q; cout<<x.c<<endl;
}
x.d=x.a-x.b;
operations operator * (operations r)
cout<<x.d<<endl;
{
r.e=r.a*r.b; x.e=x.a*x.b; 21
return r; cout<<x.e<<endl;
} }
OUTPUT :
Enter 2 values : 20 20
Addition -> 40
Subtraction -> 0
Multiplication -> 400
22
Unary and Binary operator
using Friend functions
23
Unary and Binary operator
using Friend functions
• When unary operators are overloaded using friend
function, it takes one reference argument (object
of the relevant class)
26
• where op is the overloaded operator and y is
the argument.
The operators that cannot be
overloaded using Friend function
• Assignment operator =
• Function call operator ( )
• Subscripting operator [ ]
• Class member access operator(.)
27
Binary operator overloading using friend
function
#include <iostream>
using namespace std;
#include <conio.h> s operator+(int a, s s1)
class s {
{ s k;
public: k.i = a+s1.i;
int i,j; k.j = a+s1.j;
s() return k;;
{ i=j=0;} }
void disp(){cout << i <<" " << j;}
void getdata(){cin>>i>>j;}
friend s operator+(int, s);
};
28
Binary operator overloading
using
friend function
int main()
{
s s2;
s2.getdata();
s s3 = 10+s2;
s3.disp();
return 0;
}
29
Unary operator overloading using friend function
class A
{
int a;
//Friend Function Prefix
public: friend void operator++(A &obj)
A(){ } {
obj.a=obj.a+1;
A(int ta) }
{ a=ta;
} }
void display()
{
30
cout<<"A"<<a;
}
Unary operator overloading using friend function
int main()
{
A obj(100);
obj.display();
++obj;
obj.display();
obj++; 31
obj.display();
return 0;
}
Overloading the
Assignment Operator
(=)
32
Assignment operator overloading
rules
The operator function for the assignment operator
are inherited by any derived class.
36
Overloading The Subscript Operator []
#include<iostream.h>
void main()
const int SIZE=5;
{
class array
array a1;
{
int i;
private :
for(i=1;i<=SIZE;i++)
int a[SIZE];
{
public:
/* control is transferred to the operator
int operator [] (int i) function call int operator [] (int i) */
{
return i; cout<<a1[i]<<"\t";}
} }
}; 37
Overloading of new and delete
Operators
• To handle memory resource in a customized way, the
memory allocation operators new and delete can be
overloaded.
• It helps the programmer to gain full control over the
memory resource and to handle resource crunch
errors such as Out of Memory.
• An application that overload new and delete
operators by itself, can easily detect memory leaks
(improper usage).
38
#include <iostream>
Example
using namespace std;
#define NUM 5
class Number
{
private:
int *series;
public:
void *operator new(size_t)
{ Number *num;
num = ::new Number;
num->series = new int[NUM};
39
return num;
} }
Example (cont’d)
void operator delete(void *n)
{
Number *num;
num = (Number *) n;
delete (int*) num->series;
::delete n;
}
void input();
int large (void);
40
};
Example (cont’d)
void Number::input() int Number::large()
{ int i; { int i, max = 0;
for(i =0; i<NUM; i++) for(i=0;i<NUM;i++)
{ { if(max < series[i])
cout<<“Number[“ max = series[i];
<< i+1 <<“]=“; }
cin >> series[i]; return max;
} }
} 41
Example (cont’d)
int main()
{ Number *l_num = new Number;
cout << “Enter Numbers:” << endl;
l_num->input();
cout<<“Largest Number”<<l_num->large();
delete l_num;
return 0;
}
42
Overloading
stream extraction (>>)
and
insertion (<<) operators
43
Overloading stream extraction
(>>) and insertion (<<) operators
• The stream extraction operator >> and the
stream insertion operator << to input and
output fundamental-type data using.
• The C++ class libraries overload these binary
operators for each fundamental type,
including pointers and char * strings.
• We can also overload these operators to
perform input and output for user defined
data types such as classes. 44
Overloading stream extraction
(>>) and insertion (<<) operators
(cont’d)
• The overloaded stream insertion operator (<<) is used in an expression
in which the left operand has type ostream &, as in cout <<
classObject.
• To use the operator in this manner where the right operand is an object
of a user-defined class, it must be overloaded as a non-member
function.
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
}; 46
Overloading stream extraction (>>) and
insertion (<<) operators (cont’d)
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
48
Overloading stream extraction (>>) and
insertion (<<) operators
- Example - 2
49
50
51
Types of conversion
52
Types of conversion
56
Class Type to Basic Type
• Some times a situation may occur that a class
type needs to be converted to a basic type.
• As done previous, the conversion cant be
done using the constructor since, it requires a
class object on the left-side of the type
conversion.
• For such situation “ Conversion function” , an
overloaded casting operator must be defined.
57
58
#include <iostream> //overloaded int cast
#include <conio.h>
using namespace std;
operator int(){
class rectangle int r;
{ r = len * br;
int len; return r;
int br;
public:
}
};
rectangle() { }
int main()
void getdata() {
{ rectangle r1;
cout<<"Enter value for length : "; r1.getdata();
cin>>len;
cout<<"Enter value for breadth: ";
r1.display();
cin>>br; int area;
} area = r1;
void display() // call the operator int() to cast our class to int.
{ cout<<"\n Area of rectangle is :
cout<<"\n\n The length : "<<len; "<<area<<" cm2"; 59
cout<<"\n The breadth : "<<br;
} getch();
}
OUTPUT:
The length : 12
The breadth : 34
Area of rectangle is : 408 cm2
60
Point to remember while defining a
conversion function
• The conversion function must be a non-static
member function of the class.
• The conversion function cannot have an argument
list or a return type.
• Like a constructor, the conversion function can also
be called explicitly.
• The complier implicitly invokes the conversion
function whenever a class object present on the right-
hand side of the assignment statement does not match
with the data type of the variable present on the left- 61
hand side of the assignment statement
Class Type to Another Class Type
• When one class type is to be converted into
another class type, the class type (object) that
appears on the right-hand side is known as
the source class and the other side is known
as destination class.
• Conversion of one class type to another can be
handled by using
• Constructor (OR)
• Conversion function 62
• However , if the constructor is used for
conversion, it must be defined in the
destination class.
• Let us explain this with an example
program using constructor.
• In this example, the conversion of US
currency to INR currency is handled using
class to class conversion by means of
constructor (or) conversion function
63
#include <iostream>
using namespace std;
class CUR_IND // destination class
{
int in;
public:
CUR_IND() // constructor defined in destination class
{
in = 0;
}
void putvalue (int w) { in = w; }
void display()
{
cout<<"Currency in indian Rupees :" << in <<endl; 64
} };
class CUR_US //source class
{
int us;
public:
CUR_US (int n) //parameterised constructor
{
us = n;
}
operator CUR_IND () // conversion function present in
// source class of the destination
class
{
CUR_IND ci;
int ru = us * 65;
ci.putvalue(ru);
return ci;
}
void display() { cout<<“Currency of US "<< us <<endl; } }; 65
int main()
{
CUR_US cu(100);
CUR_IND ci;
ci = cu ; // implicit call to conversion function
// ci = CUR_IND(cu); // explicit call to conversion function
cu.display();
ci.display();
return 0;
}
66
OUTPUT:
Currency of US 100
Currency in Indian Rupees :6500
Press any key to continue . . .
67
Note:
68
Thank you…
69