SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
Operator	overloading	and	type	conversion		
	
C++	tries	to	use	the	user	defined	data	types	much	in	the	way,	the	built	in	data	types	are	
used.	C++	has	the	ability	to	add	special	features	to	the	functionality	and	behaviour	of	
already	existing	operators	like	arithmetic	operators.	The	mechanism	of	giving	special	
meaning	to	an	operator	is	known	as	operator	overloading.	In	C++	one	can	overload	any	valid	
operator	of	C++	except	the	following:	
Ø Class	member	access	operator	(	.	)	(dot)	
Ø Class	member	access	operator	when	pointer	is	used	(	.*	)	
Ø Scope	resolution	operator	(	::	)	
Ø sizeof	operator	
Ø Conditional	operator	(	?	:	)	
Operator	overloading	is	used	to	make	most	of	the	standard	operators	(available	for	built	in	
data	types)	to	be	used	with	user	defined	data	type	items.		
v Operator	overloading	is	applicable	only	to	the	existing	operators,	no	new	operator	
can	be	created	using	operator	overloading.		
v The	overloaded	operator	must	use	at	least	one	user	defined	data	type.		
v Through	operator	overloading	semantics	of	an	operator	can	be	enhanced	but	the	
syntax,	the	general	grammar	like	number	of	operands,	precedence	and	associativity	
remains	the	same.		
v Hence	when	an	operator	is	overloaded,	its	original	meaning	is	never	lost.	for	
example	if	+	is	used	to	find	sum	of	integers	or	floats,	then	it	can	only	be	used	to	find	
sum	but	after	overloading	+	can	be	redefined	to	find	sum	of	objects	or	to	
concatenate	strings	but	not	to	subtract	numbers.		
v However	either	a	friend	or	a	member	function	can	be	used	to	overload	the	
operators,	some	of	the	operators	like						=	,	(	)	,	[	]	and	->					cannot	be	overloaded	by	
using	fried	function.		
v Binary	operators							+	,	-	,	*	,	/				must	return	a	relevant	value.		
Syntax	for	operator	overloading	
Operator	overloading	is	implemented	through	a	special	member	function	known	as	
operator	function.	Syntax	for	defining	an	operator	function,	when	it	is	a	member	function	of	
the	class:	
Return_type		class_name		::		operator		op_symbol		(arguments	list	)	
{	
	 ................Function	body..............	
}	
Ø Here	return_type	is	return	type	of	function.
Ø The	declaration	and	definition	statement	of	operator	overloading	function	must	
have	keyword	operator.	
Ø op_symbol	is	any	valid	operator	symbol	of	C++	which	can	be	overloaded.		
Ø Operator	overloading	function	can	be	a	member	function	or	a	friend	function.		
v Friend	function	–	if	the	operator	overloading	function	is	a	friend	function,	
then	it	will	be	called	without	any	object,	hence	the	number	of	operands	
required	for	the	operator	(to	be	overloaded)	are	to	be	passed	as	arguments	
to	the	function.	For	example	to	overload	unary	minus	(-)	there	will	be	one	
argument	to	the	function	and	to	overload	plus	(	+	)	two	arguments	will	be	
required.		
v Member	function	-	if	the	operator	overloading	function	is	a	member	function	
of	the	class,	then	it	will	be	called	using	object	of	that	class.	The	object	used	to	
invoke	the	member	function	is	implicitly	passed	to	the	function,	by	the	
compiler	and	hence	that	is	made	available	in	the	member	function	directly.	
So	every	time	this	function	will	be	called	the	compiler	will	have	one	active	
object,	whose	data	members	can	be	used	directly.	Therefore	the	number	of	
arguments	in	the	operator	overloading	function	will	be	one	less	than	actually	
required.		For	example	to	overload	unary	minus	(-)	there	will	be	no	argument	
to	the	function	and	to	overload	plus	(	+	)	only	one	argument	will	be	passed	to	
the	operator	overloading	function.		
Steps	of	operator	overloading	
Ø Create	the	class	whose	objects	are	to	be	used	in	operator	overloading.	
Ø Declare	and	define	the	operator	overloading	function	which	can	either	be	a	public	
member	function	of	the	class	or	a	friend	function	to	the	class.	
Program	1:	operator	overloading	of	increment	(unary)	operator	++	using	
member	function.	
/* program to increase the private data items of an object by
10 each. */
#include <iostream>
using namespace std;
class fruit
{
int bananas, mangoes;
public:
fruit ( int b, int m) // constructor
{ bananas = b;
mangoes = m;
}
void display( )
{
cout<<”n number of bananas : “<< bananas;
cout<<”n number of mangoes : “<< mangoes;
}
void operator ++( ); // operator overloading
// using member function
};
void fruit::operator ++( ) /* member function to overload
unary operator does not accept any argument */
{
bananas = bananas + 10;
manges = mangoes + 10;
}
int main( )
{
fruit basket1(5,9) , basket2(15, 5);
cout<<”n ...... initially no of fruits in
baskets.........”;
basket1.display( );
basket2.display( );
++basket1;
++basket2;
cout<<”n after using overloaded increment ++ operator
with objects ”;
basket1.display( );
basket2.display( );
return 0;
}
Output:	
...... initially no of fruits in baskets.........
number of bananas : 5
number of mangoes : 9
number of bananas : 15
number of mangoes : 5
after using overloaded increment ++ operator with objects
number of bananas : 15
number of mangoes : 19
number of bananas : 25
number of mangoes : 15
	
Program	2:	operator	overloading	of	unary	minus	(	-	)	using	friend	function	
//to find negative of a complex number, using friend function
#include<iostream>
using namespace std;
class complex
{
int real, img;
public:
complex( ) { } // default constructor
complex (int n) // constructor with one parameter
{ real = img = n; }
complex (int r, int i) //constructor with two parameters
{ real = r;
img = i;
}
void display( )
{ cout<<”n complex number = “<< real<<” +
“<<img” i”; }
friend complex operator – (complex c)
}; // end of class
complex operator – (complex c) // operator function
{
c.real = - c.real;
c.img = - c.img;
return c;
}
int main ( )
{
complex num1(5, 8), num2;
cout<<”n original complex number......................”;
num1.display( );
num2 = - num1; // calling operator function
cout<<”n negative complex umber.......................”;
num2.display( );
return 0;
}
Output:	
original complex number......................
complex number = 5 + 8 i
negative complex number.......................
complex number = - 5 + -8 i
	
Program	3:	overloading	arithmetic	operator	(	+	)	to	find	sum	of	two	objects	
(using	member	function	to	overload	+	)	
/* program to overload + operator to find sum of two time
values given in hours and minutes */
#include<iostream>
using namespace std;
class time
{
int hours, mins;
public:
time() // default constructor
{ hours = mins = 0; }
time( int x, int y ) // parameterised constructor
{ hours = x;
Mins = y;
}
void show() // member function shows time
{
cout<<”n time = “<<hours <<":"<< mins;
}
//overloading '+' operator using member function.
time operator+(time); // operator function
};
/*operator function to overloading '+' operator using
member function defined outside the class */
time time::operator+(time t)
{
time temp;
int m = mins + t.mins;
temp.mins = m % 60;
temp.hours = hours + t.hours + m / 60;
return temp;
}
void main()
{
clrscr();
time t1(5,45), t2(2,30), t3;
t3 = t1 + t2; //operator function called – see note
t1.show();
t2.show();
cout<<"n Sum of times ";
t3.show();
return 0;
}
Output:	
time = 5 : 45
time = 2 : 30
Sum of times
time = 8 : 15
	
Explanation:		
In	the	statement		 t3	=	t1	+	t2;	
v t3	stores	the	value	of	object	returned	by	operator	overloading	function.	
v Because	operator	+(	)	function	is	a	member	function,	it	can	only	be	invoked	by	using	
an	object	of	the	same	class.	t1	is	the	object	which	has	the	responsibility	of	invoking	
the	operator	function.	Hence	data	items	of	t1	are	accessed	directly	in	operator	
function.	
v The	operator+(	)	function	accepts	one	argument	of	type	class	time.	t2	is	accepted	by	
the	function	as	actual	parameter.		
Overloading	+	operator	using	friend	function	
With	the	following	changes,	above	operator	overloading	which	is	done	by	using	member	
function,	can	also	be	done	by	using	friend	function.	
	 Using	member	function	
	
Using	friend	function	
Declaration	of		
operator	
overloading	
function	
time	operator+(time);			 friend	time	operator	+	(time,	time);	
	
	
Definition	of	
operator		
overloading		
function	
time	time::operator+(time	t)	
{			
		time	temp;			
		int	m	=	mins	+	t.mins;	
		temp.mins	=	m	%	60;	
		temp.hours=hours+t.hours+
m/60;	
		return	temp;			
																																																		}																																																		
time	operator	+	(time	t1,	time	t2)	
{	
	 time	temp;			
	 int	m	=	t1.mins	+	t2.mins;	
	 temp.mins	=	m	%	60;	
				temp.hours=t1.hours+t2.hours+m
/60;	
	 return	temp;			
}	
	
Example	4:	overloading	relation	operator	equal	to	(	==	)	to	compare	private	
data	items	of	two	objects.	
Following	friend	function	can	be	used	to	overload	==	operator	to	compare	two	time	values.	
This	function	can	be	added	in	proper	sequence	in	the	above	program.		
class	time	 Declare	the	operator	==
{	
								//...	as	defined	in	above	program....	 	
							friend						bool	operator	==	(time	t1,	time	t2)	
};	
function	as	friend	to	class	
time	
	
bool	operator	==(time	t1,	time	t2)	
{	
									return	(ti.hours	==	t2.hours	&&	t1.mins	==	t2.mins);	
}	
	
	
Define	the	operator	
overloading	function	
	
if	(	t1	==	t2	)	
								cout<<”n	both	time	values	are	equal	to	each	other	“;	
	
	
Now,	==	operator	can	be	
used	in	main	program	to	
compare	two	objects			
	
	 Type	conversions	in	C++	
Type	conversion	is	the	process	of	converting	one	type	of	expression	or	item	into	another	
type.	Type	conversion	can	be	implicit	or	explicit		
Implicit	/	Automatic	type	conversion		
Implicit	type	conversion	is	applied	when	data	items	of	different	types	are	intermixed	in	an	
expression.	This	type	of	conversion	is	performed	by	the	compiler	itself	so	that	no	loss	of	
data	or	information	takes	place.	C++	compiler	converts	all	items	of	expression	into	the	
largest	data	type	present	into	the	expression.	
v For	example,	if	an	expression	contains	items	of	the	types	like	float,	double	and	long	
double,	compiler	will	implicitly	convert	all	types	to	long	double.		
v Unsigned	long	integer	is	the	longest	integer	data	type,	hence	if	one	item	in	the	
expression	is	of	the	type	unsigned	long	integer,	then	all	int	and	short	data	type	items	
will	get	implicitly	converted	into	long	integer	data	type.		
An	example	to	demonstrate	implicit	type	conversion	
If	following	are	the	items:	
char	choice;			int	numi;					float	numf;				double	numdb;	 long	double	numld;	
Then	implicit	conversion	for	an	expression	given	below	will	be	like:
Explicit	type	conversion	/	type	casting		
Explicit	type	conversion	is	also	known	as	type	casting	and	it	is	implemented	by	using	
following	syntax	
(data_type)	expression;	
For	example	if	there	are	variables	like		
int	m	=	35;	 int	n	=	6;	 float	x;	
x	=		m	/	n;		 	 //here	m	=35,	n	=	6		 so	x	=	5.0	
x	=	(float)	m	/	(float)	n	//	here	m	=	35.0,		n=6.0	 	 so	x	=	5.8333	
	
Conversion	between	basic	and	user	defined	data	types	
The	conversions	discussed	above	do	not	require	special	code,	as	only	built	in	data	types	are	
used	for	conversion.	Special	programming	is	needed	for	conversion	between	user	defined	
data	items	and	basic	data	type,	because	compiler	need	to	understand	the	structure	and	
memory	requirement	of	user	defined	data	type	before	conversion.	Different	types	of	
conversion	are		
§ Basic	to	user	defined	data	type	(class)	
§ User	defined	(class)	to	basic	data	type	
§ One	user	defined	(class1)	to	another	user	defined	data	type	(class2)	
value	=	(choice	/	numi)					+					(	numf	*	numdb)								-										(numf	+	numi)									+									(numld	/	numf)	
	int																			 double																						 float																 long-double	
double
long-double
long-double
The	expression	will	give	result	in	long	double	type	after	implicit	conversions.
Conversion	from	basic	data	type	to	class	type	
Conversion	from	basic	data	type	to	class	type	can	be	performed	by	using	a	single	parameter	
in	a	constructor.	The	example	below	will	explain	it	in	detail	
Program	1:	to	demonstrate	basic	to	class	data	type	using	constructor	
// program to convert quantity of weight into kilograms and
grams
#include<iostream>
class weight
{
int kg, gm;
public:
weight ()
{ kg = gm = 0; }
weight ( int w ) // this constructor will
convert an integer to class type
{
kg = w / 1000;
gm = w % 1000;
}
void display ( )
{ cout<<”n kg = “<< kg<<”t gm = “<<gm ; }
}; // end of class
int main ( )
{
int wgm;
cout<<”n enter weight in grams : “;
cin>> wgm;
weight mangoes ;
mangoes = wgm; // wgm gets converted into kg
and gm
magoes.display ( );
return 0;
}
	
Output:	
enter weight in grams : 4520
kg = 4 gm = 520
	
	
Conversion	from	class	type	to	basic	type	
C++	has	the	option	of	overloading	casting	operator	which	can	be	used	for	conversion	from	
class	to	basic	type.	The	function	used	to	overload	casting	operator	is	usually	called	
conversion	function.		
Syntax	of	conversion	function	 Rules	to	define	conversion	function
operator	type_name	(	)	
	{	 ..........	
															..........	
	function	body	
	..........	
...........	
	
}	
• It	must	be	a	class	member	
• It	must	not	have	a	return	type	but	a	return	
statement	
• Conversion	function	cannot	accept	any	
argument		
• Being	a	member	function,	it	is	invoked	by	an	
object	and	values	of	that	object	are	used	inside	
the	function.	Hence	no	argument	is	passed	to	
conversion	function.	
	
Program	3:	demonstration	of	conversion	function	to	convert	from	class	to	basic	type	
// program to convert weight in kilograms and grams to grams
only (class to basic type)
#include<iostream>
class weight
{
int kg, gm;
public:
weight ()
{ kg = gm = 0; }
weight ( int k, int g )
{
kg = k ;
gm = g ;
}
operator int ( ) // conversion function
{
int w ;
w = (kg * 1000) + gm;
return ( w );
}
void display ( )
{ cout<<”n weight in kg & gm : “<< kg<<” kg
“<<gm << “ gm “; }
}; // end of class
int main ( )
{
int wfruits , wvegies ;
weight fruits(3 , 500 );
weight vegies( 2 , 250 );
fruits.display ( );
vegies.display ( );
wfruits = fruits ; // invokes operator function
and return weight in grams
wvegies = vegies; // invokes operator function ,
behaves as vegies.opertor int ()
int total_weight = wfruits + wvegies;
cout<<”n total weight of fruits and vegetables : “<<
total_weight;
return 0;
}
	
Output:	
weight in kg & gm : 3 kg 500 gm
weight in kg & gm : 2 kg 250 gm
total weight of fruits and vegetables : 5750
	
	
One	class	type	to	another	class	type		
Conversions	from	one	class	to	another	class	type	can	be	carried	out	either	by	a	constructor	
or	by	a	conversion	function.		
If	objA	is	object	of	class	A	and	objB	is	the	object	of	class	B.	To	convert	class	B	data	type	to	
class	A	data	type	following	statement	can	help	
																			objA	=	objB	;		
For	this	conversion,	class	B	is	known	as	source	class	and	class	A	is	known	as	destination	
class.		
When	a	class	is	to	be	converted,	casting	operator	function	can	be	used	in	source	class.			
																																																															operator		type_name	(	)	
To	convert	source	class	type	data	item	to	destination	class	type	data	item,	above	function	
should	be	a	member	function	of	the	source	class	and	type_name	should	be	the	type	of	
destination	class.		
Program	4:	to	demonstrate	the	conversion	from	one	class	to	another	
// program to illustrate class to basic and class to class
conversions
# include <iostream.h>
class one
{
int code,items;
float price;
public:
one(int c,int i,int p)
{
code = c;
items = i;
price = p;
}
void showdata()
{
cout<<"n CODE= "<<code;
cout<<"n ITEMS= "<<items;
cout<<"n VALUE= "<<price;
}
int getcode()
{
return code;
}
int getitems()
{
return items;
}
int getprice()
{
return price;
}
Operator float () // class to basic
conversion, returns float value
{
return items*price;
}
}; // end of class one
class two
{
int code;
float value;
public:
two()
{
code = 0;
value = 0;
}
two(int x,float y)
{
code = x;
value = y;
}
void showdata()
{
cout<<"n CODE= "<<code;
cout<<"n VALUE= "<<value;
}
two(one obj1)
{
Code = obj1.getcode();
Value = obj1.getitems()*obj1.getprice();
}
}; // end of class two
main()
{
one ob1(1000,20,150);
float tot_value;
two ob2;
tot_value=ob1; // invokes operator function of class
one
ob2 = one( ob1); // conversion from class two to class
one
cout<<"n item from class one ";
ob1.showdata();
cout<<"n VALUE= "<<tot_value;
cout<<"item from class two ";
ob2.putdata();
}

Contenu connexe

Tendances

Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
Alisha Korpal
 

Tendances (19)

Function in c
Function in cFunction in c
Function in c
 
Functions in c
Functions in cFunctions in c
Functions in c
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
C functions
C functionsC functions
C functions
 
Built in function
Built in functionBuilt in function
Built in function
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Function
FunctionFunction
Function
 
Functions
FunctionsFunctions
Functions
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Function in C
Function in CFunction in C
Function in C
 
Function in c
Function in cFunction in c
Function in c
 
user defined function
user defined functionuser defined function
user defined function
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 

Similaire à M11 operator overloading and type conversion

C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
TAlha MAlik
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
iammukesh1075
 

Similaire à M11 operator overloading and type conversion (20)

Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Week7a.pptx
Week7a.pptxWeek7a.pptx
Week7a.pptx
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
C++
C++C++
C++
 
Lecture5
Lecture5Lecture5
Lecture5
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 

Plus de NabeelaNousheen (8)

C++ tokens and expressions
C++ tokens and expressionsC++ tokens and expressions
C++ tokens and expressions
 
Digital Logic
Digital LogicDigital Logic
Digital Logic
 
Mcq's for internal exam
Mcq's for internal exam Mcq's for internal exam
Mcq's for internal exam
 
Local simple ecosystem ppt
Local simple ecosystem pptLocal simple ecosystem ppt
Local simple ecosystem ppt
 
Ecosystem
EcosystemEcosystem
Ecosystem
 
Global_Warming_notes_ppt_slideshare
Global_Warming_notes_ppt_slideshareGlobal_Warming_notes_ppt_slideshare
Global_Warming_notes_ppt_slideshare
 
File_Management_in_C
File_Management_in_CFile_Management_in_C
File_Management_in_C
 
User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.
 

Dernier

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Dernier (20)

WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 

M11 operator overloading and type conversion

  • 1. Operator overloading and type conversion C++ tries to use the user defined data types much in the way, the built in data types are used. C++ has the ability to add special features to the functionality and behaviour of already existing operators like arithmetic operators. The mechanism of giving special meaning to an operator is known as operator overloading. In C++ one can overload any valid operator of C++ except the following: Ø Class member access operator ( . ) (dot) Ø Class member access operator when pointer is used ( .* ) Ø Scope resolution operator ( :: ) Ø sizeof operator Ø Conditional operator ( ? : ) Operator overloading is used to make most of the standard operators (available for built in data types) to be used with user defined data type items. v Operator overloading is applicable only to the existing operators, no new operator can be created using operator overloading. v The overloaded operator must use at least one user defined data type. v Through operator overloading semantics of an operator can be enhanced but the syntax, the general grammar like number of operands, precedence and associativity remains the same. v Hence when an operator is overloaded, its original meaning is never lost. for example if + is used to find sum of integers or floats, then it can only be used to find sum but after overloading + can be redefined to find sum of objects or to concatenate strings but not to subtract numbers. v However either a friend or a member function can be used to overload the operators, some of the operators like = , ( ) , [ ] and -> cannot be overloaded by using fried function. v Binary operators + , - , * , / must return a relevant value. Syntax for operator overloading Operator overloading is implemented through a special member function known as operator function. Syntax for defining an operator function, when it is a member function of the class: Return_type class_name :: operator op_symbol (arguments list ) { ................Function body.............. } Ø Here return_type is return type of function.
  • 2. Ø The declaration and definition statement of operator overloading function must have keyword operator. Ø op_symbol is any valid operator symbol of C++ which can be overloaded. Ø Operator overloading function can be a member function or a friend function. v Friend function – if the operator overloading function is a friend function, then it will be called without any object, hence the number of operands required for the operator (to be overloaded) are to be passed as arguments to the function. For example to overload unary minus (-) there will be one argument to the function and to overload plus ( + ) two arguments will be required. v Member function - if the operator overloading function is a member function of the class, then it will be called using object of that class. The object used to invoke the member function is implicitly passed to the function, by the compiler and hence that is made available in the member function directly. So every time this function will be called the compiler will have one active object, whose data members can be used directly. Therefore the number of arguments in the operator overloading function will be one less than actually required. For example to overload unary minus (-) there will be no argument to the function and to overload plus ( + ) only one argument will be passed to the operator overloading function. Steps of operator overloading Ø Create the class whose objects are to be used in operator overloading. Ø Declare and define the operator overloading function which can either be a public member function of the class or a friend function to the class. Program 1: operator overloading of increment (unary) operator ++ using member function. /* program to increase the private data items of an object by 10 each. */ #include <iostream> using namespace std; class fruit { int bananas, mangoes; public: fruit ( int b, int m) // constructor { bananas = b; mangoes = m; } void display( ) { cout<<”n number of bananas : “<< bananas; cout<<”n number of mangoes : “<< mangoes;
  • 3. } void operator ++( ); // operator overloading // using member function }; void fruit::operator ++( ) /* member function to overload unary operator does not accept any argument */ { bananas = bananas + 10; manges = mangoes + 10; } int main( ) { fruit basket1(5,9) , basket2(15, 5); cout<<”n ...... initially no of fruits in baskets.........”; basket1.display( ); basket2.display( ); ++basket1; ++basket2; cout<<”n after using overloaded increment ++ operator with objects ”; basket1.display( ); basket2.display( ); return 0; } Output: ...... initially no of fruits in baskets......... number of bananas : 5 number of mangoes : 9 number of bananas : 15 number of mangoes : 5 after using overloaded increment ++ operator with objects number of bananas : 15 number of mangoes : 19 number of bananas : 25 number of mangoes : 15 Program 2: operator overloading of unary minus ( - ) using friend function //to find negative of a complex number, using friend function #include<iostream> using namespace std; class complex { int real, img;
  • 4. public: complex( ) { } // default constructor complex (int n) // constructor with one parameter { real = img = n; } complex (int r, int i) //constructor with two parameters { real = r; img = i; } void display( ) { cout<<”n complex number = “<< real<<” + “<<img” i”; } friend complex operator – (complex c) }; // end of class complex operator – (complex c) // operator function { c.real = - c.real; c.img = - c.img; return c; } int main ( ) { complex num1(5, 8), num2; cout<<”n original complex number......................”; num1.display( ); num2 = - num1; // calling operator function cout<<”n negative complex umber.......................”; num2.display( ); return 0; } Output: original complex number...................... complex number = 5 + 8 i negative complex number....................... complex number = - 5 + -8 i Program 3: overloading arithmetic operator ( + ) to find sum of two objects (using member function to overload + ) /* program to overload + operator to find sum of two time values given in hours and minutes */
  • 5. #include<iostream> using namespace std; class time { int hours, mins; public: time() // default constructor { hours = mins = 0; } time( int x, int y ) // parameterised constructor { hours = x; Mins = y; } void show() // member function shows time { cout<<”n time = “<<hours <<":"<< mins; } //overloading '+' operator using member function. time operator+(time); // operator function }; /*operator function to overloading '+' operator using member function defined outside the class */ time time::operator+(time t) { time temp; int m = mins + t.mins; temp.mins = m % 60; temp.hours = hours + t.hours + m / 60; return temp; } void main() { clrscr(); time t1(5,45), t2(2,30), t3; t3 = t1 + t2; //operator function called – see note t1.show(); t2.show(); cout<<"n Sum of times "; t3.show(); return 0; }
  • 6. Output: time = 5 : 45 time = 2 : 30 Sum of times time = 8 : 15 Explanation: In the statement t3 = t1 + t2; v t3 stores the value of object returned by operator overloading function. v Because operator +( ) function is a member function, it can only be invoked by using an object of the same class. t1 is the object which has the responsibility of invoking the operator function. Hence data items of t1 are accessed directly in operator function. v The operator+( ) function accepts one argument of type class time. t2 is accepted by the function as actual parameter. Overloading + operator using friend function With the following changes, above operator overloading which is done by using member function, can also be done by using friend function. Using member function Using friend function Declaration of operator overloading function time operator+(time); friend time operator + (time, time); Definition of operator overloading function time time::operator+(time t) { time temp; int m = mins + t.mins; temp.mins = m % 60; temp.hours=hours+t.hours+ m/60; return temp; } time operator + (time t1, time t2) { time temp; int m = t1.mins + t2.mins; temp.mins = m % 60; temp.hours=t1.hours+t2.hours+m /60; return temp; } Example 4: overloading relation operator equal to ( == ) to compare private data items of two objects. Following friend function can be used to overload == operator to compare two time values. This function can be added in proper sequence in the above program. class time Declare the operator ==
  • 7. { //... as defined in above program.... friend bool operator == (time t1, time t2) }; function as friend to class time bool operator ==(time t1, time t2) { return (ti.hours == t2.hours && t1.mins == t2.mins); } Define the operator overloading function if ( t1 == t2 ) cout<<”n both time values are equal to each other “; Now, == operator can be used in main program to compare two objects Type conversions in C++ Type conversion is the process of converting one type of expression or item into another type. Type conversion can be implicit or explicit Implicit / Automatic type conversion Implicit type conversion is applied when data items of different types are intermixed in an expression. This type of conversion is performed by the compiler itself so that no loss of data or information takes place. C++ compiler converts all items of expression into the largest data type present into the expression. v For example, if an expression contains items of the types like float, double and long double, compiler will implicitly convert all types to long double. v Unsigned long integer is the longest integer data type, hence if one item in the expression is of the type unsigned long integer, then all int and short data type items will get implicitly converted into long integer data type. An example to demonstrate implicit type conversion If following are the items: char choice; int numi; float numf; double numdb; long double numld; Then implicit conversion for an expression given below will be like:
  • 8. Explicit type conversion / type casting Explicit type conversion is also known as type casting and it is implemented by using following syntax (data_type) expression; For example if there are variables like int m = 35; int n = 6; float x; x = m / n; //here m =35, n = 6 so x = 5.0 x = (float) m / (float) n // here m = 35.0, n=6.0 so x = 5.8333 Conversion between basic and user defined data types The conversions discussed above do not require special code, as only built in data types are used for conversion. Special programming is needed for conversion between user defined data items and basic data type, because compiler need to understand the structure and memory requirement of user defined data type before conversion. Different types of conversion are § Basic to user defined data type (class) § User defined (class) to basic data type § One user defined (class1) to another user defined data type (class2) value = (choice / numi) + ( numf * numdb) - (numf + numi) + (numld / numf) int double float long-double double long-double long-double The expression will give result in long double type after implicit conversions.
  • 9. Conversion from basic data type to class type Conversion from basic data type to class type can be performed by using a single parameter in a constructor. The example below will explain it in detail Program 1: to demonstrate basic to class data type using constructor // program to convert quantity of weight into kilograms and grams #include<iostream> class weight { int kg, gm; public: weight () { kg = gm = 0; } weight ( int w ) // this constructor will convert an integer to class type { kg = w / 1000; gm = w % 1000; } void display ( ) { cout<<”n kg = “<< kg<<”t gm = “<<gm ; } }; // end of class int main ( ) { int wgm; cout<<”n enter weight in grams : “; cin>> wgm; weight mangoes ; mangoes = wgm; // wgm gets converted into kg and gm magoes.display ( ); return 0; } Output: enter weight in grams : 4520 kg = 4 gm = 520 Conversion from class type to basic type C++ has the option of overloading casting operator which can be used for conversion from class to basic type. The function used to overload casting operator is usually called conversion function. Syntax of conversion function Rules to define conversion function
  • 10. operator type_name ( ) { .......... .......... function body .......... ........... } • It must be a class member • It must not have a return type but a return statement • Conversion function cannot accept any argument • Being a member function, it is invoked by an object and values of that object are used inside the function. Hence no argument is passed to conversion function. Program 3: demonstration of conversion function to convert from class to basic type // program to convert weight in kilograms and grams to grams only (class to basic type) #include<iostream> class weight { int kg, gm; public: weight () { kg = gm = 0; } weight ( int k, int g ) { kg = k ; gm = g ; } operator int ( ) // conversion function { int w ; w = (kg * 1000) + gm; return ( w ); } void display ( ) { cout<<”n weight in kg & gm : “<< kg<<” kg “<<gm << “ gm “; } }; // end of class int main ( ) { int wfruits , wvegies ; weight fruits(3 , 500 ); weight vegies( 2 , 250 ); fruits.display ( ); vegies.display ( ); wfruits = fruits ; // invokes operator function
  • 11. and return weight in grams wvegies = vegies; // invokes operator function , behaves as vegies.opertor int () int total_weight = wfruits + wvegies; cout<<”n total weight of fruits and vegetables : “<< total_weight; return 0; } Output: weight in kg & gm : 3 kg 500 gm weight in kg & gm : 2 kg 250 gm total weight of fruits and vegetables : 5750 One class type to another class type Conversions from one class to another class type can be carried out either by a constructor or by a conversion function. If objA is object of class A and objB is the object of class B. To convert class B data type to class A data type following statement can help objA = objB ; For this conversion, class B is known as source class and class A is known as destination class. When a class is to be converted, casting operator function can be used in source class. operator type_name ( ) To convert source class type data item to destination class type data item, above function should be a member function of the source class and type_name should be the type of destination class. Program 4: to demonstrate the conversion from one class to another // program to illustrate class to basic and class to class conversions # include <iostream.h> class one { int code,items; float price; public: one(int c,int i,int p) { code = c; items = i; price = p;
  • 12. } void showdata() { cout<<"n CODE= "<<code; cout<<"n ITEMS= "<<items; cout<<"n VALUE= "<<price; } int getcode() { return code; } int getitems() { return items; } int getprice() { return price; } Operator float () // class to basic conversion, returns float value { return items*price; } }; // end of class one class two { int code; float value; public: two() { code = 0; value = 0; } two(int x,float y) { code = x; value = y; } void showdata() { cout<<"n CODE= "<<code; cout<<"n VALUE= "<<value; } two(one obj1) { Code = obj1.getcode(); Value = obj1.getitems()*obj1.getprice(); }
  • 13. }; // end of class two main() { one ob1(1000,20,150); float tot_value; two ob2; tot_value=ob1; // invokes operator function of class one ob2 = one( ob1); // conversion from class two to class one cout<<"n item from class one "; ob1.showdata(); cout<<"n VALUE= "<<tot_value; cout<<"item from class two "; ob2.putdata(); }