Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
169 views

CSE1002 Operator Overloading CPP

Operator overloading in C++ allows operators to have special meanings for user-defined types. It provides flexibility in creating new definitions for operators when applied to classes. The key points are: - Operator overloading gives normal C++ operators like +, -, * additional meanings for user-defined data types. - Common operators like +, -, * can be overloaded using member functions or friend functions. - Overloaded operators must have at least one operand of a user-defined type and preserve precedence and associativity. - Overloading allows defining custom behaviors for mathematical or other operations on user-defined types.

Uploaded by

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

CSE1002 Operator Overloading CPP

Operator overloading in C++ allows operators to have special meanings for user-defined types. It provides flexibility in creating new definitions for operators when applied to classes. The key points are: - Operator overloading gives normal C++ operators like +, -, * additional meanings for user-defined data types. - Common operators like +, -, * can be overloaded using member functions or friend functions. - Overloaded operators must have at least one operand of a user-defined type and preserve precedence and associativity. - Overloading allows defining custom behaviors for mathematical or other operations on user-defined types.

Uploaded by

Vibhor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Operator

Overloading
1
Operator Overloading
• C++ has the ability to provide the operators with a special
meaning for a data type.

• This mechanism of giving such special meanings to an operator is


known as Operator overloading.

• It provides a flexible option for the creation of new definitions for


C++ operators.

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.

simply defined as to create new definitions


for operators.

Data type conversions is closely connected


3
with operator overloading.
The Overloadable Operators
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]

4
The non-Over loadable
Operators

• Class member access operator (. , .*)


• Scope resolution operator (::)
• Size operator ( sizeof )
• Conditional operator (?:)

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 general form is[syntax]:


return type classname :: operator op(op-arglist )
{
function body
}
 where return type is the type of value returned by specified operation.
 operator op is the function name.
 Op- operator being overloaded.
6
 The op is preceded by a keyword operator.
Rules for
Operator overloading
 Only the existing operators can be overloaded.

 The overloaded operator must have at least one operand that is of user
defined data type.

 The procedence and associativity of an operator


cannot be altered
 The basic meaning of the operator should not be changed.

 Overloaded operators follow the same syntax rules of the original


operators. They cannot be overridden.

 The number of operands that an operator takes 7


cannot be changed
The steps involved an operator are

1. Create a class that defines a data type that is to


be used in the overloading operation

2. Declare the operator function as either a


member function or a friend function inside the
class

3. Define the operator function either inside or


outside the class

4. Use the operator in the main() function 8


Unary & Binary operator using
member functions
• When unary operators are overloaded using member functions it
takes no explicit arguments and return no explicit values.

• When binary operators are overloaded using member functions,


it takes one explicit argument.

• 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)

• When binary operators are overloaded using friend


function, it takes two explicit arguments.
24
How an overloaded operator can be invoked
using member functions?

• In case of Unary operators, overloaded operator


can be invoked as:
op object_name or object_name op

• In case of binary operators, it would be invoked as:


Object . operator op(y);

• where op is the overloaded operator and y is the


argument. 25
How an overloaded operator can be invoked
using friend functions?
• In case of Unary operators, overloaded
operator can be invoked as:
operator op(x);

• In case of binary operators, it would be


invoked as:
operator op(x,y);

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

//Friend Function Postfix


friend void operator++(A &obj, int dummy)
{
obj.a=obj.a+10;
}
};

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.

 Friend functions cannot be used to overload the


assignment operator.

 You can overload the assignment operator (=) just as you


can other operators and it can be used to create an object
just like the copy constructor. 33
Overloading the assignment operator (=)
• Following example explain how an assignment operator can be overloaded.
#include <iostream>
using namespace std;
class Distance
{ private:
int feet , inches;
public:
Distance()
{ feet = 0; inches = 0; }
Distance(int f, int i)
{ feet = f; inches = i; } 34
void operator=(const Distance &D )
{ feet = D.feet; inches = D.inches; }
void displayDistance()
{ cout << "F: " << feet << " I:" << inches << endl; }
};
int main()
{ Distance D1(11, 10),D2(5, 11);
cout << "First Distance : "; D1.displayDistance();
cout << "Second Distance :"; D2.displayDistance();
// use assignment operator
D1 = D2;
cout << "First Distance :“; D1.displayDistance();
35
return 0;
}
Overloading The Subscript /
Array Index Operator[ ]

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.

• Similarly, the overloaded stream extraction operator (>>) is used in an


expression in which the left operand has type istream &, as in cin
>> classObject, and the right operand is an object of a user-
defined class, so it, too, must be a non-member function.

• Each of these overloaded operator functions may require access to the 45


private data members of the class object being output or input, so
these overloaded operator functions can be made friend functions of
the class for performance reasons.
Overloading stream extraction (>>) and
insertion (<<) operators (cont’d)
#include <iostream>
using namespace std;

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;
}

istream & operator >> (istream &in, Complex &c)


{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part ";
in >> c.imag; 47
return in;
}
Overloading stream extraction (>>) and
insertion (<<) operators (cont’d)

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

To enhance the conversion between built-in


data type with user – defined data types
following three types of conversion are
involved:
1. Basic type to class type
2. Class type to basic type
3. One class type to another class type
53
Basic Type to Class Type
• This conversion is accomplished by defining a
constructor of the class that accepts an
argument of any basic type, which is to be
converted to class type.

• To understand the concept of conversion,


consider the below example. 54
#include <iostream>
#include <conio.h> void display()
{
using namespace std;
cout<<"\n\n The meter :
class measurement "<<meter <<"m";
{ cout<<"\n The centimeter :
int meter; "<<cm <<"cm";
int cm; }
};
public:
measurement() int main()
{ meter =0; cm = 0;} {
measurement r1;
measurement(int i) int km = 2;
{ r1 = km; // implicit call to the
//constructor
meter = i*1000;
cout<<" The measurements are ";
cm = i*100000; r1.display();
} getch(); 55
}
OUTPUT:

The measurements are

The meter : 2000m


The centimeter : 200000cm

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:

Enter value for length : 12


Enter value for breadth: 34

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:

The use of both the constructor and the


casting operator function for the same type
conversion should be avoided, in order to
prevent ambiguity in the function call.

68
Thank you…

69

You might also like