0% found this document useful (0 votes)
17 views

Practical No19.oop

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

Practical No19.oop

Vhhgjku hhjhghhu hvjkhg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Object Oriented Programming Using C++ (313304)

Practical No. 19: Write programns to overload unary operator using


Member function
Friend function

I Practical Significance:
The concept of operator overloading helps to assign the new meaning to the
existing operator and helps to extend the concept of polymorphism.

Industry/Employer Expected Outeome(s)

CHNI
This practical is expected to develop the following skills as:
l provide additional meaning to the unary operator using member function and
friend function.
2. Define anduse the overloaded operator function in the class.

I|I Course Level Learning Outeome(s)

Implement Polymorphism in C+t.


IV Laboratory Learning Outcome(s)

1. Implement unary operator overloading using member function.


2. Implement unary operator overloading using friend function.

V Relevant Affective Domain relaied outcome(s)

1. Select proper programming environment in C++.


2.Follow ethical practices.
VI Relevant Theoretical Background
Operator overloading
Operator overloading is a type of polymorphism m which an operator is
overloaded to give user defined meaning to it. The mam purpose of operator
overloading is to perform operation on user defined data type. For eg. The '+
operator can be overloaded to perform addition on various data types. Operator
overloading is used by the programmer to make a program clearer. It is an important
concept in C++.

Syntax:

Retum type classname :: operator OperatorSymbol (Argument List)

I/Statements;
Maharashtra State Board of Technology (K Scheme) 107
Object Oriented Programming Using C++t (313304)
The operator keyword is used for overloading the operators.
There are a few operators whichcannot beoverloaded are follows,
1. Scope resoluticn operator ()
2. sizeof
3. member selector(.)
4. member pointer selector ()
5. ternary operator (?:)
There are some restrictions considered while implementing the operator overloading.
1 The number of operands cannot be changed. Unary operator remains
unary, binary remains binary ctc.
2. Only existing operators can be overloaded.
3. The precedence and associativity of an operator cannot be changed.
STATE 4. Cannot redefine the meaning of a procedure.
TheUnary Operators can be overloaded by using:

HTRAS
1. Member Function
2. Friend Function
In the case of anon-static member function,the unary operator should rot have
an argument.
In the case of a friend function, the unary operator should have only one
argument.
They perform various operations such as incrementing/decrementing a value
by one, negating an expression, or inverting the value of a boolea11

. Unery Operator Overloading Algerithm/Steps:


Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step4: Using the function getvalue() to ge! the two
numbers.
Step 5: Define the function operator ++ to increment the
values
Step 6: Define the function operator - -to decrement the
values.
Step 7: Define the display function.
Step 8: Declare the class object.
Step 9: Call the function getvalue()
Step 10: Call the function operatort+ ) by incrementing the
class object and call the function display.
Step 11: Call the function operator -- 0 by decrementing the
class object and call the function display.
Step 12: Stop the program.

Maharashtra State Board of Technology (K Scheme) 108


Object Oriented Programming Using C++(313304)
VII Resourees Required
Sr. Name Quantity Remarks
Resource Specification
No
1 Tomputer Any desktop or laptop computer with/One comnputer system for
Systnm cach student
basic configuration
Operating Windowvs /LINUX One for each computer
system system
Software Turbo C++ Version 3.0 or any One for cach computer
other system

ANIC
VII Precautions to befollowed
1. Handle computer systenn and peripherals with care.
2. Follow safety practices.

IX Exercise:

1. What is function overloading and operator overloading?


2.State output of the folloving code:
#include <iosream.h> class
Distance {
private:
int feet: int
inches:
public:
I/ required constructors Distance(0
feet= 0:
inches= 0;

Distance(int f inti)
feet= f:
inches= i;

void displayDistance(Q{
Cout <"E: "<<feet<<"I:"<<inches <<endi;

I/overloaded minus (-) operator Distance


operator- (0{
feet= -feet; inches=
-inches;
return Distance(feet, inches);

int main)
Distance Dl(ll, 10), D2(-5, |1);
-Di:
DI.displaylDistance();
Maharashtra State Board of Technology (K Schemne) 109
PAGE Nn

DATE

EXercise
iFunction OUerlo acing
EuctOn f e t ure

hct you to dere


mmwl tiple cwith t h e Same
but OIth d f f e r e n t pat cmete
Correct f u n c t i h S elected
base d atgLmento p a s s e c
Oen the colled

ier
Oaaneters
type Dwrm ber
The loe CanOt

be

iOperator Overoaclinq
thcut
featture
to

uth dato tpe


objectG
nmoe intitive
Some Sizeof,?: )
CanNot OUer loocled
opertor Overlodio iS done by
ceinnq fubCtioh g t a t uGe Special
Ope r a t o r
PAGE NO.:

DATE:

Ohay operotor - CminwG uSiq


member Letion

#icluce < i o t t e a " b


HicldeConio "h

Gaple

pri vote

public
Veid getclatcCinta,intb,into,

ptctcLc)

Void operator
PAGE NO.

DATE:

VOid main CO

Sample s:
SgetclatCL Ci,20, 30),

Gdisplay
ge tch O:

whaty perator
-Cminus using ftienc
urion

#inclce2i0sreom}
DGtance
private
SceetbIhceG
Dietace3 fOet(o, inches (o)?
DStanceCint int i )
feet =
incheG
PAGE No..

DATE:

frienc Distone operctor -CcOnGt.

liGplOy DiGtance C) const

Dist c n c e o e r t o r - CcONSt DIGtance

tetu Distanee C-cfeet,-d

DistcCe
clrscrCO
Distasce D3-DI

Dy dis plDiSton ce c

ge teh
Object Oriented Programming Using C+(313304)
-D2:
D2.display Distance():
return 0:

function and friend function


2. Overload the unary operator -(minus) using member
X C++ code:
Write "C++" Code for above exercise on the blank pages attached at the end of practical,

XI Resources Used
OF TECHA
Sr. Name of Resource Suggested Broad Specification Quantity
No.

XII Result(s)

XIII Conclusion
...s....h-e.ar.c.ti.Gad........sahAJe
.have...eaTta.AMte..prOgramS
t.eerle.uNay..Fer.cAtOr.Sig
Simember Fuction2 Fiend unction
XIV Practical Related Questions
Note: Below given are few sanple questions for reference. Teacher must
design nore such questions so as to ensure the achievement of identified CO.
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)

Write a C+t program to overload unary operators (++) increment and(--) decrement
by using member function and friend function.
Write C++ program to find the area of various geometrical shapes by
function overloading. (eg. Area of circle, circumference of circle etc...)

Maharashtra State Board of Technology (K Scheme) |10


(PAGE NO
DATE

PracicculRelatecl 0westios
"00er locc uNaryoerotrs uging
member

la Counter

private Couti

C o t e r (O Cont Co)L?

COwnto Cint c ) i c o u t CC ?

Cowteroseratottt C

retTthS

endlj
PAGE NO:

DATE:

int

COhter

c-cl is p l y

Ci· ciS play

wain
friend

#incluce< ioSt n e m h

clase Countek

pHV o t e int

public
PAGE No
DATE

ried CoLnter onerator--Cconter

uoid displaO
CoLnt

operator++ C Counter c)

returnc

int

clclisploy

ge tcc)
PAGE NO.:

DATE:

+ ihcluce<coiO h

VOid
areaCint l, int b)

clrsCr c
COt
racliug

arec Cr):

intl
Breacith
QreaCI bi;
float Sl
Cout< E n t e r t h e sie.

Cout <<\EtT the


ci he)
height
PAGE NO
DATE

Cow t <4 \ E n t e r t h e Baee


cin> baal
Cout<<" Areaofthe thiagle
GEeaC bal,he

U0id ate a C i n r )

iteS
reg=3
+he circle"2<res:

int es
tes b
Cowt 4 rea of t h e restcnele<tesL;

foat area C o a t g)

reNCres2

foat orec cEo Qt b, Hoat h

res3,
ATE

res 3 Ob
e t u n Cres3);
Dbject Oriented Programming Using C++ (313304)
3.Complete the following table:
Programn Code Write & justify
Output
Doimt oneG
a)#includeciostream.h> dimenionG
class 3D
int x, y, Z: ireret
OF

TECH
publie:
3D (intA
a0,K
int b-O, int c-O) The elementS
Xa;
y=b;
PointoheG
dimensi onS
3D operatort+0 Cfter incer
X=X+ 1;
y=yt l; 3,y:5,z6
Z+ 1;
Point t o G
return *this;
clise orS
3D operator ++(int) before
icremet
3Dt= *this:
the
X=X+ 1; Cre

y =y+ 1; lentS
Z=Zt 1; re
return t:
Point t u o S
BD show()
diensiorzG
cout<<"The elements are:\n" cout<<"x:"<<this-x<<". CferiCheme
y:<<this-y <<",z:'"'<<this-z: nt re: -

Dci8,y:2,2:
int main(0
3D pti(2,4,5), pt2(7,1,3):
cout<<"Point one's dimensions before increment are:"<<
ptl.show(0:
*ptl;
cout<<"Point one's dimensions after increment are:"'<<
ptl.show):
cout<<"Point two's dimensions before increment are:"<<
pt2.show):
pt2++;
Maharashtra State Board of Technology (K Scheme) 111
Object Oriented Programming Using C+-+ (313304)
cout<<"Point two's dimensions after increment are:"<
pt2.show0:
return 0:

b) #include <iostream.h>
Outpt
/C+t program to show unary
/ operator overloading Eee t
#include <iostream> ncheS
using namespace std: Secremet

STATE
RA
class Distance
|public:
int feet, inch;

/Constructor to initialize
/ the object's value
Distance(int f, int i)
TECH
this->feet =f:
this->inch = i;

/Overloading(-) operator to
l perform decrement operation
l of Distance object
voidoperator-)
feet--;
inch--;
cout << "nFeet & Inches(Decrement):" <<
feet << " << inch:

Driver Code
int main(0
Distance d1(8, 9);
I/Use (-) unary operator by
l single operand
-dl;
return 0;

(Space for Answers)

Maharashtra State Board of Technology (K Scheme) 112

You might also like