Вы находитесь на странице: 1из 11

Radhabagale.Blogspot.

Com
. \

, c·hapter 5: . .
_- .; --
-· Polvmorphism andVirtua·1Classes _· ···---:
~ , . ,- ~~- . ia!':~~- ;..-;.·, i~ . . . . .. . ·. ·. . . •, . .

. .
) ,•

·: ..
:

·. .

. ..
l

.

'.
• )

.. ' . .

.
.

.
• •

.

.. . . . . . . .

· Polym6.rphis-
. . .
irt: -_ A process
. . . . .
of obtaining· two . --..:..__:_ . . . . . . . . .

: . o:f_ op erator qr -v i ·i;:_t_u_c1l ke:.YWO~ds from sin


- -.as po~ymorphi.sm. ( The stra ight f()rW_q <d -mE
'ct- .6per_a tion_s -from an _operat_o r is r:
impor·tal)t' · chara·c terS -o f · ·ooP. i'f · an OpE
u;,€c;r ··eithe_r - with · different" -_-data types
~peci:f ie_o .·_ funGt.ion _· 0Pe_rclt,0r ·_ ·: wil 1 or- :
00 l vmo·r.nh·i r .: h~h-~ -~T; ·A ·'r. . ~-.. .i . t- · . . ~. ~ ~ --~, ~ -+- h ~ '"'1 ~ , v-
Chapter 5:

wh il e(inch>=l2 )
Polvmorphis_m and Virtual Classes • . . .. { f eet++;
) ~~\ . more operations with the hel iric h-=1 2;
Polymorphism: i,. process of obta ining two '~~ oper~ _or. function ~ ~
- · vwords f rom sing . . t or · . - n }
of O era tor or V 'rtu , - - forwarctmeaning is doing ·. WO . more form s void
as polymorphism . The straight . lymorphismJ It is one of th "<<inch;) showdist() {cout<<"feet is inch is
'-- . -· -· . rator is po . f . . e " << feet << ''
or operations .from. an ope • tor or function o a class . i -
OOP If an opera t ~ distance
important characters o f · · or different argumen s then th operator+(distance d )
us ed either with different data ty_p et work differently. According e { distance dl;
. operator w1 1 . ·t · to
specified . function or 1 ssified into two ypes as dl.feet=feet+d.feet;
• ·t is further ca
1
polymorphic behavior, . . dl . inch=inch+d.inch ;
1 . Design time polymorphism if(dl.inch >=l2.0 )
2 . Run-time po l ymorphism r·tual function , pure virtual ' functi on .{ dl.feet++ j dl.inch=dl .inch - l i .O ; }
Different f ea tures of OOP as vi _ g etc are used in · po_1 ymorp · h ism.
· · Ot·' return (dl) ;
ct·
F.

cvpe cast 1n
operator overloa ing , - . _ t because a form of code •€an : be used };
. 't •- very 1mportan .
implementation , 1 1 " It also helps to develop app 1 ica tion and int main()
in the different ouLputs ·f
· th components o a
program into other cla.ss a nd modules.
• ,.,. •
It I d~stance distl, dist2, dist3;
ex ten d ing e by customizing the part.i-cul ar requirement. d~stl . getdist{);
adds new data types , operat_ors ·
. ?lst2. getdist () ;
For exampl e . . f d
+ is ei th~r used as add1t1on o operan s
or concatenating two st ·
, ,. , . . ring s dist3=ctistl+dist2; ; / ,../-/JJfJ JbrrrA .:i. ,,c Ued
bl;! 1 ~1'j"
into single string . "-" Gurung". cout«" \n object 1 distance is " · dist 1. showdist·();
i . e 3+4"7 and "Ram "+"Gur ung - Ram ·cout<<:" \n object 2 distance is "· dist2. show_d~ t P"i·
. cout<< "\n object 3 distance is " · d · 3 h d · • · i··
getch() ; 1st .s,'.~~-·J:s t ,t ;
a. Compile-time Po1Vmorf1hism _ . . _. . .. ~, return O;
If a value 01. ou tput of . a n operator
. . or
.. func.t.,:on
·...· ··· .is available
· 111 mor.e Lfl an
. . . }
fo rm due to va lue asso c iation at_ compiJ:er time or. at program design
1
time th en it is called. cornpile- t iriif:.:,po.lymorphi sm. Most_ly , a prci<:;_rammer
i dentify the requirement a nd pol ymoi;-phj,c nature. Accordlng to , progr_a ~er .'' il~M ·_'··MP.LE 2: ~AP to demonstrat~Junction overloadin~b.iz9qmRutin.g volume of different shapes cs.

·
expe rience or expertise o -·
. . crea
· t'ivitv'·
,· ,• _. a code. or · operator
· can _be· · used in. to · #~nclucl.e <1os~::eam.h> C, t,fT/JJ)ecf ➔ ."/,.1.¥/hw?e., hely~o'l~•Jm· . ~

muit iple cases . The keyword, .·•_o.E'erator ' .. is . used to _dedn·e· ~esign_ ti me
. .
~lp.. c:lude . <.conio .. h> · · f ., • :: . /' lv(11l)Jk l,,J;r,
intvolume( i nt); • ., .:,,. . -.: · fNv · r
po lymorphi s{ll ' It is also sal~e~~} S i;,arh b:nch~g. Thus, _lL unl_y so l ves
common type of problems. Dd rrng the compi~atic~ .- compiler binds on" dot,ble volume(double, int) ; :.\~;~;, '.·,· , · . 'I( . ~ .. · _1,.~f I
ooerator with mul tipl e ope_i:sitors or one function with othe.r functions a nd
long volume(long, int int). ~ ;%~~- (Ar:}'£,, _. Clo/n141-
a~nerate multip le outp uts : 'j:t '.is les s secure in valu.e binding .
· com.men types are operat<?-r: overloading and ·o verriding. ·~-nt
1 rr,ain ()
cout<<" \i1 Volume•::, '::-\~}
is :·'i<:<-:"/; ·~.-,
volume(lO ); ~1/)r'ff:;\!}f>rD~)v(h{.~~q
or=,L1t_J,_',,,/fJ>
,, . /\t/1'
- :1'-W_'-li'Ae,?~
cou t.< <"\n Vo l um~ . ts ,;':!:<Volume (2 . 5, 'A'};
b. Run-time Polvinomhism cout « "\n Vol 41l)E; i,,,::; • "«volume {1001 , 7, 10) ;
If a va lue or. out pu t · o f a function is obtained more than 1 form due to
multiple assQ.ciat:\.on of variable s at the time of program execu tion 1s ~=~~:~) ~\t ···t:;:;;v · h'lf~,
1 vl)fiuJ (~~N
called run - time · polymorphism. It also uses the operato r s and functions
for generation of output. I t is more powerful than compil e time int vqlum_'7,-(Jp'.!;,, s)' {return (s*s*s) ; }
polymorph ism. It hides th e internal det a ils of program binding . It is do ubl e ·.:v_o'lu\n~ .(do uble r , int h) {return (3 : 1415*r*r*h);}
also called as li'lte binding or dynamic binding. I t depends on e nd - user or lo r,g .1.01\wie:("iong 1., int b ,. int h) {return (l*b*h);)
. ,\;.~ ..
use;:, glve n dat ,; . It solves the complex problem. Mostly , ru n - time
polymo rphism is defined by keywo rd virtual. There a re • va ri ous fc rms of i/E:X(-\~P,l:E.3: WAP to compute th!;l sum of two complex number by using operator overloading
run-tiine polymorphism implementation as virtual function , pure v irtual. #ihh,cl ude <iostream.n> · · ·.
func ti on and ab=tract class or function . #ir{; iude <conio.h> '
// EXAMPLE 1WAP to compute the distance between two objects by using +o rator overloading class complex
#inclu~e ~i os~r-iam .h> 11)(/l')f( ( . \ private: floc.t x,y; · . . .
#:1nc luae <co ,110 ,h> ~- ~ .::.!.J.~--,JC144~.J.Lf~ public : complex(}{x;.0 . 0;y=0 .0; }
class dista nce 81'~ tmVt · complex (tloat real, float imag)
pri~a t e: in t feet; fl oat inc:h ; {x=real.; y,.;imag;}
public: distance() {feet=O; inch=O.O ; } complex ope rator+ (complex c )
•J
distance( i nt f , flo at i} {feet=f ; inch=i ; J {complex temp;
Vo, getdist {) {cout« " \ n Enter distance i n feet & .i _n che s " ;
t ernp. x=x+c , x;
· temp . y=y+c . y;
cin>>feet>>inch ;
vo id displ ay() {cout « x « " +j "«y« " \n"; }
(5 7) Prepa red by tlhim Bhandari, (58] Prepared by flh im Bhandari, Oxford College of Engineering and Mana gement
Oxford College of Engineering and Management
Radhabagale.Blogspot.Com

:::::::;:
...._
.....:-:,.•,,.1r.:.i...

..,...........
.. 0
'Iba t1 u
.s , ......
t2 tetdataC,
t l+t2

:return O,

- to create I class time with constructor having three


rs, minutes and second taken from user. Add time
to add user given two sets by usmg +t me
overtoading
lin..... ..,.fo
Ci.Ntnaab>

cla . . lM
b>

( pri,,.. iat llr•, ain•, HC,


; ••t. !11110 (bn-0,ain•-0,HcaO,)
IM(iat b, int m, int
(
nt •in()
point ptl,
ptl. inp.atcord ()
)(hr alaaU-.N099) cout<< \n Before unary operato ainu•
•o ,etdata O (cout<<' n Enter hours, minu ptl duplayc rd()
and o conch
.,b9_.••IIIMM111111Mtnt
Pr p r by Oid dCo m Pr• rtdbJ
Radhabagale.Blogspot.Com
co nv e r ts th e inlie ger da t a
- ptl i va lue to 1t s
operator minus'' ; co r responding foot and inch. passe d_ a s an arg umen t.
cout<<"\n After unary
ptl . displaycord() b. conversion between class and b .
1 n this . type of conve as1c tvnes
gotch () i coriverted into·. basi ·:;non, the attribute value of ob ject from a cl ass i s
return O; Jt is defined throu;h ata types such as integer or float or character s.
0 verloading . The op · User-defined object's class in the form of operato r
. erator fu t · . b · c da t a
cype which takes no ar nc ion is def ined as an over l oaded as i
basic data type and gument. It converts the data member of a n obJ ec t t o

TV. pe COOVerSIOII , /.( 4_$!hi~ . . d. ,. · ~b·icct is always executed ;vithd the .help of The ·syntax is ope rat ):.e t~rn. a basic data i tern .
. 1 . . )11 ·ihicct ,m ,.•1c11 c . i:, • { / /b d or as1c· type () ,
I11 \ l\ll' ' ,·,·crv ,·,,111p11t:11t,m 1s ,:1,,, ' '.
• .
t"d·t·i we willsettheoperatorsan ~unction to
j' , t 1 th,· 11:tt urc O •1' ' · · - . Th
e i t ··
0
y of. the operator overloading
ea ures of class t 0. b .
li111c1i,,11 ini1i:11,·tl by nu1111(). ,\cc,,n Ill!; ' . · • 1· • ·ti" ,,cts the value from mstruchorr.bu_t· 111 some i- It must be a me . as1c · type conversion
,, t · • · ·111 0b1,·ct c ll'CC 1 "' 1 · bl · ·
,•cnn:il,· rrqui1\·d ,,utpul. ",,me nn,~. · · . . t· ,nts It means for a c ass vana e or attribute
" I I ,J in11111/outp11t ~t.1 ell1c . d ii- No return ·datamber function of a class
..1,c, 11 ,cr 11·ill enter v:1 uc t H'<'llg 1 .
• , .
. ol)'morphism. The given or compµte value of · ii No type will be specified
,. • . . . 1·11i ,n 1c r1111-l1mc p . F I l · argument will b
,.. tlu,· di:m~cs 1h,· 11':ty ,11 c,mipu · ' · · • v ·iied into nonnal fom1.. or examp e value of //
WAP t . e .passed to thi s type o f function
. - . . J· t r,rm ihus must 1"' c,111 c . . ·d . . . . b" . 0 convert the ob' t
:ill rib111,·s m,1y 11,1t 111 , tan ,m ' . fr.,ct 9 inch. It 1s snnply · one _m o ~ect oriented •include <i Jee of class into basic data t ype
,li,1:111,·c as -15 ind1,·s mus! be wntt,·n as 3
. ' . I I I ·111 ,ftYP<' ('(llll't'fSlt)ll.
wll 1Ill' 1' ' -
..
. .• ', 11· . rt d I
I " ostream.h>
#i nclude <conio . h>
,nrc,,•r:11n111m~
" ~
rh,· :1111,,1n:llll' type.· ,,,n" ' '
.- •hi side data is automatic.a . y conve e to eft side
.. 1.. 1· ,11 111 ,., 111 , that I11c, 11g s· •.
1
, in ·ill c·ises of user. defined type. n user defined data
. ;I· c lass length
{ . Pri'vate : int foot, inch ;
.. t· . 1. ·rsi,,n ruk l':mnot app 1) • • . . · :" 1. kn ty
'"P
. ''· 1111, t)l"-' l,, . "'n ' ·,. 'l''ltll\ . l\lll(II\C . ()\ITT~--Ives • T)'pe. convers1 ,•, ·'
bn. 1s a. so • own bl as pe castino. " public : length(irit ft , · ·int in ), {f.oot=ft; in,c h=in;)
t1·1x·
. m: mu,t , d11K' .,·,,n ' · t. • '\Uf l ·)s• l·lt·tr"c'l•'r · to inteoer-
\ ~, . ... 1.11
float 'into dou e, etc. In case of ·length operator+ int () { i nt len;
~,,1p,• ,,f ,·,111\'t"rsit,n is 3ut,,m:1 i, . 1 •• ,
o ' ..
v ·rsion as , ·.:, '·· . . len';'foot*l2.+ i:nch ';_ /
. ,; I ' • J •yds tis-'[ ddi1wd d:ll:l tyv,· con l . ' . ·> .
1..)l) . 11;.•rt· ~u~~ -' . t ..... b ~si c and cl ass t yp~s, . . retu rn·, l ~n-; : . l
._· ,._"'UV~l' S l1-.'tl !:' t:>t WCe. ll .... .... t.., ' C t vp'eS . void display () cout<<"\n · _ob j e_ct size fo o t is << fo ot << "
11

.. . .. . . "' 11 l•l""twe l? n c l 3. ~5 <i nd 3s 1 . • • ; ..;- inch i's_"«inch; l


t· . , .·n, <'- a h . • of a c lass .,t o another c l ass }; .
\.',,.,n\·1.' r :d . :- n l'c?t i.-·e~n an obJe C1.. . -~· .. \.'
... -~- . int main u

3. Coov,.f'SIID
• - a rwee• Usie and class iypes
r . b .. .
·. '·· .
, . u,er-delined ·type the conversion funct10n should be defined
. · · · _( leng th bb j1(12 , 10) , ob j2(1 4,5);
· int lenl , len2 ;
.'>-:>
·•r
r • Jl ' l tn.lll\ :\ :!.'ill J\1'.'c 1l •1 '
• I

.m,,u~\T
«'r.':, 1..: hn_·_
[l
'; ,.. .,..
."\..I l'l~i c'\:l ~
. ' . ..
1, .. in the form .of constructor. This constructor functJon takes a smgle
l ,..!-..') .. • ·.
.
.l eril=ob j 1; \:'- ~. •;:
.cout« " \ n Object 1 is '! ;.6bjJ'. di s play();
.,~umcnt ,,n,.-,ic: d.lla 1~f'<"- ' 1 fun c t .:.on (basic data type l cout« "\n Leng th in i'n°c h ·.. is.' "« lenl ;
Tb: s\·:1tJ. ~ :~ c0nstr_uct or _ .
, t ;:,di· of t he C;)nst ruct or runction l l eni=ob j 2; . .., •· '. ....
. ~c..
. ,v:1 s t r.=i t~ c-oJwe rsi on c f object from basic to clas s type cout«;' \n Ob ject·,' ~ - is• ., (:obj2. display ( J. ;
A.;F : .."'
cout<<"\n Length , in f nch is "<<len2;
.:·.: : "..l...i;: , i . --. :; cr-e 3.:a. h~
getch() ; _. ~•,1t-\;~ , i
: ::-..-.:lt.:.i~ , 0.:-n i 0. h_> return O; ,, •. <'-
~:
1
"::\<c_:/::~:'i:~t, f ee: , : nc~; I
11
b .i:~ .,(~'.
t he a ov~ :c~gr am the attributes of an object like obj i (1 2 , l C, )
: :.::, : : -: : ier.gtr. \ : r. : l e:1 )
fcct =: e:;. 1: ; co nverted into , t ~ he s is class to basic da t a type conversion.
' . =, .·--qy
.:. :-.-.::-. =:C: T2~%1: ;
c. conversion between an obiect ol aclass to another class
" : J .:: :. :':: : 3 y (l 1 :;:--.:: «" \ :i : c<:it is " <<f e e t< <" Inc h is "<< i nch; ) In OOP,. flata-val~e of an object from a class can be converted into object of another classes without
dcviatin$ ~ value is called class to class conversion. The volume of one object or its weight when
!ll 011f class will be the sa.me even it is shifted to another class. ln geometric theories, the relation of
bJse'-an'd perpendicull.r is given by its _angle. Thus, an object of one system is equivalent even if it is
ir. JDOther class. For example: body temperature in degree and radian is same but expressed by
diiforent values.
/ ' '.·/AP to create a class polar. th e n use ·+operat o r o v e rl oac ir.g t o c ~c a t,;
ne w rectangular object* /
E :1.clude <iostr•iam.h >
#i n clude <math . n>
#inc lude <conio . h>
_c :-.; : :t ·.·.:: ~::~, s : c : e:r'. e:1:s co:y~·e rt s r. he ba si c data c la s s po lar
: : :~ : : 5 : : =~~ :: ~::~ :~e ~~:? o f co~struct o=. i: p r i va te: : l uat raC. ius , angl e ;
?Uo l ic : fl ·1at g~t z () { ~et ~r~ r ad i us·=oz (a ~g le );}
O·<lord College of Engineering and Management [6 2] Pre pared by Bi im Bha ndari, Oxford College of Engineering and Mana gement
Radhabagale.Blogspot.Com
--- . ------------------~~--~~----------1111

ir. t e.i:,,.~.
float
p 1blic: voi d getda~c'·-
;-;ic,,,•
( ,.~ _. i •. t a, float bl
- ..-~c: • a; P. . . "r-ei.
void she,., ( ~~--=-o; :
{
:".,...,..c-:.,~;
n Pric~ : .. .......?r i ce;
};
int main()
{ iter;. ' '°"'Of:',#
,. i ten [s i ze] ;
iter:. • ct-p;
int x,i ; ,
float y;
t ~ c;a5ti~g one class tr, an0ther class for(i•~;irsize;i++)
I c:ut<✓• ,n Input code and price for i,teiq"<< 1+1 ) ;
c1.n.,,,..,z,..,.,,.y ;
p-:.-getdata( x, y);
p++ ;
}
r..~9.0;J for(i•O ; i<size;i++)
;;t y /.""4"/ ;ycr;s7;, I cout<<"\n Iteir : "<'<' Li. H) ;
~ ZC'J,..,:-:'!nate .. ,..,.,..zCV.,..." nJcoordinat!: d-;,5how (l;
d++;
c,perat { float r= ~grt(xco•xco+yco•;co);
fl~at a• at~n(7co/xco1; getch(} ;
rn P0L(a , r); return O;
I

~le, ratiius;
~le• ;radiu:s•';; J
nt a, iI t rJ (angle•a;r,,tJ11;s•r: J this pointer
dt play O ( r..ouv ✓ ",n P.arJfos l, si:,"ddl p9(nt r which points the ~rrent object f rc,m tr.e same -::la
with the h p c,f ' this ' \;.e'jword is known as this pointer. In 'JOP , tr. ~
ffl/•.rm•~-•,~a gle;J pointer i, d fro10 •1arious functions such as pointing an eni:ue rla
for a.J 'b:]eet; pointir11 the multiple values of dif f <c, r er,t -:.t)ects at
:.im!: anct.,. J2rt'lcessing differen• data type~ b'/ uilng single oper«tor . . t
11 fHi!:. ' is a pointer that P"ints to the object for: which tr 1
ti, lon is called. For example the function call abc.ma x (} will set th
r,< h .r·r: this to the address of the object abc. The starting addres ~ 1
the SaJlle as the• addreECs of the first variable i n the clas, stI ~cture. •
/ /WAP to show the details of employee 'tli.th the help r,f tr.is po nter
4include <iostream.h>
linclude ~conio.h?
iinclude <string . h~
dass person
( private: char nalll'![lSJ; int ag,;, ;
Polnrer ro o•trtt'i public: pr;rsonl:har •s,int a) {~trcpy(naine, g •a ; }
l'olll(Cr l (lflC of OOP fi fl 1".C( mwupu!,1ti9n. II allows lo handle data with some per:ion· !,person: :cr€;ater (person &z)'
1
of di1r< 1 appl•c from l)flC lor.ation to another. (1cncrally, • or & I 1 ( Cz.age>•age)
return z;
ope, n1or ire u da1a I fer from one object to another duno' o ~.fo rd Collt&e of Engineering and Managem nt
tr, 3) l'rcp,,rt>a by 81,,n, Rhrindor, 01ford Col!l•ge of Engineering and Management [64; Prepared by Bhim Bht1ndori,
one
e l s e ret ur11 ' t i1is ; prot ec t ed :
J
int width;
void di splay () int height;
( cout << " \n Name
cout << " \n Ag e;
J;
// Derived classes
class Rect_angle: pub li c
}; { public : Shape
i nt main() 3( " S . " 20 )
{ pe rson Pl("Hari" ,3 0) , F2 ("Gopa l" , 40), P amir, ; in t get Area ()
person P=Pl . g r ea ter( P3) ; . ret u r n (Width* h.
cout « "\n The .person with greater age is ";P . displa y(); ); e i ght) ;
P =Pl.qreater (P2 }; class Tr i angle: p ublic
cout « ;'\n The person with gr eate r age is " ;P.display(); ( pul:>lic : Shape
get c h( ); int getArea ( )
ret\lrn 0; { return (width
l; * height) 12 ; )

i nt main ( )
l\bslracl Classes Rect.angle Rect;
l\n interf ace des c ribes the be ha vio r o r capabi li ti~:,,_ of a Ctt · class
wit hout committ ing to a pa rti c ul ar imp l ement at i on of'·. 1:l:\<:;:t cl.ass. The C++ Triang l e Tri;
int~r f aces a re implement ed using abstract . clas,;';~S an{I these abstract. Rect . setWidth(S);
cl a ss es s hould not be confused with data abstr~~~.Jt~-_which is a concep t Rect . setHeight( 7 ) .
o f keeping i mpl eme ntation details separate from _·as~·o:c1.ated data. · A cl'a ss
i s ma de abstra c t by decl a r ing a t least o~e . . of, rts . functions as pure
I. II Print the area ' of the
co~t « "Total Rectan le
object.
~: Tr~ . setwidth(S) ; . g area: " « Rect. getA;~~ (,l. « endl;
vic·tu a l f unc tion . A ure virtual function is· .s ec,.fied b lacing " = 0 .,
in i t s dec l ar a t ion as fo ll ows : ., Tn . setHeight(7).
cla ss Box II Pri~t the area'
I.
of the object. .
( cout « . "Tota l Triangle area: " « .,Tif._s ge~A:~a ( ) << e ndl ;
return O; 1 1
.
publi c: '. /:···
I I ru r e vi rtua l function
virt ,,al doub l e ge tVo lume I I o/ :'.:.' \t::;;-
p r i va t e : C
doubl e l e ngt h; I I Le ngtti of a box c}-- i.L.
doub l e b r eadt h; 1 1 Br ea dth of a box ~\.~ ~(i'V

) doubl e he igh t ;

T\ · 0 purpose of a n a b.s t rac t


1 1 He ight of a box

cl ass (o fte·n r eferred t o as a n F,BC) i s t o


r "''
I
pr ov ide an appropr i a t e ba se c l a s s fr om which othe r c l asses ca n inh e rit .
Abs trac t cl as ses ca nnot be us ed tQ..._inst·a nt.i ate objects ?nd s erves only as I
an interf ace. ·Attempting t o in s t a ntia te a n obj e ct of an abstract
cl ass ca use s a compi l ati on e rr o r. Thu s , if a subcl a ss of an ABC :10,,,<3 t o
. :
(.!) void teaddtd(I r 1 ( l
be i nst antiat ed , it hcis t o i mpl eme nt eac h of the virtual fun c t i o ns , wh i c h
mea ns that i t s uppor t s t he i nt e r face dec l a r e d by t he ABC. Fc1 ilu r c 1 0
I L___, ft')emkr fun lh' o fJ
ove rr iile a pur e virtual f unc ti on in a d e r i ve d cl as s , t he n at t empt i. n<J
{h viTlu oJ vo; d readdiJ-q JJ (
r
'co i nst:111ti ate obj ec t s of t hat c l a ss, i s a comp i lati on e rr or: . t.: l c1,1:;c• f; ,
t hs:i t c~n~9e used t o in s t a nti a t e obj ~c t s are ca ll e d con c r et,1 c l as ses.
Ab st ra q'. 'Cl ass Ex ample:
~ vtr~ QJ {u" cJ,'~"
C0ns ider the fo llowing e xampl e whe r e pare n t c l ass provide s c1 n i 11Lc:rrc1ce
to t he base cla s s t o impl eme nt a fun c t i o,'i call e d ge tArea () :
@ v·1(kAJ vc-ic r('() ddrA 11 =o;
riincl~de ci o~ t r~am>
using n.,me s pac2 std ;
L-~--....)?{i y 1Y/-u u} fa11dfJi 1
(.

// Base cl ass

class Shape
( p ub li c :
II pure v r tu a l (unc t io n provid in g i nterf ace f r a mewor k.
: irtu;,\ int get l\rea () - O; ~ pu ,e \'><4-4
\'Old se tl'I dth ( cnt w) ( width s; ;
~"
\'Oid s,·L1\• . qh• (i nt i) ( heigh t = h;
:0 5: Prepared by /Jhim Ghondon, Oxford Coll ege of Enginee rin g and Manage me nt
[6G] Prepared by Shim Bhandari, Oxford Coll 0 g,, of Engineeri ng an d ·Management
Radhabagale.Blogspot.Com
~in c lud~~i0s t re~m . h>
Chapter 6 #i ncl ud~ <con io .h>
ca ns t int ma z= 2 ;
a. Template >t a dded i n 1 989 t o de pl oy the sa mp l e t . template <class T>
T emp .1a ·c e1·s an e w f eat ure o f C. , . . df' G
o be l ongs unde r sa me fami ly. It is e lnect b class stack I
t he nwnber o f prog ra m~ two method s for the i mp lemen t at i on they a y
c d ' temp la te' Th re a r e 0
· . re { p r iva t e:T s tk[ma· .
,.e y,1o r '· · - . templat e It is esse n t ia l to imp l eme p ub l ic · z] ; i n t top;
clas s t emplate _a ndd fun c t dio1~unct ' o n s~ that same t hing c an b e Used ·?t . · stac k () {
l · o rphism rn ata a n • . in void p ush (T data ). ' top= - 1 ; )
po ym I a no ther wo rd template 1 s know n as ' mac r o , t h t
d iff o rent data types . n • • a {if (top=-
•- d f . d class o r fun c t ion to mu l t1p 1 e time s as per requ ir ed e l se =ma x- l )cout« " \n St:<ick i s full";
•,·eoeat
. s ,,t he ande.ine
valu e s . ·
Temp l ate i· s a 1 so k nown a s ~ er·c n
rog r arnrning } {top++ ; st k[ top ] =data ; }
da t a typ: s . ._ ro gram then same prog r am ca n be used to t h e . 1 . ,.
beca us e if there is a p
.
. bl
f family among in t, float, do u e, ca r , e tc . .
h . l~t T ()OP() {if(top==-1) ~
of links making tre e o ( c o ut << " \
n s tac k i s empt y" · return NU LL · } ~
~'0.
~
e l se (T d _ ' '
/l , vfemplate Class: . . ,·. . i n t ! ~in ( ) {clrs c r(} ; ata- s t l:[ t op ]; t op--; return dat~a;)
1.,/t:-~ ··'
)U /\ 1 ,.. data s truc u "'
t r " c a n be us <>d for t empl a t e ha v i ng p ri v ate
• · .
a ttn butes .
cind

r Ln
O 11 ·
0
, .

1
et hods i s )·nown
1
1 s eno e
as Lem l ate c l ass •
pu o i c m t d by k~ ywo rd template and < >. For ex amp l e , to
r, BC as t empl a t e we use the syntax as
. . · --
de f i ne a Cl ·
a ss stac k <int> s l ;
s l . pu s h(lO} ; s l.push(2 0 ) ;s l . pu sh (30);
~
1
{ W t emplat e <cla s s T> cout<< "\n"<<s l . pop(} ; c out<< " , " <<s l . pop() ;6ou t< <" , " <<sl . pop( : ;
Y Her e , t empl a t e i s keyword to de fin e . th e t emp late ,. cla s s i s ke yword to get c h( ); •
de fin e the data type of class as c l ass a nd T i s , a va riable t o h a nd l e t he r.e turn O;
template class• · .. }
. ;: ·. . . . .
'l'c,rnolate s are ve ry use ful whe n i mp l er.i_e n t :i ri.g_ ge ne ric const r ucLs l ii'
ve c t e>rs, stacks, li s ts a nd que ues whicii',··can..·• be us ed with · a n y a r b i t r a;: •
t1~ ~~: TO IMPLEMENT THE . TEMPLATE CLASS TH/1.T CONVERTS
~ 'ay,, r,,-l'ly)
FROM VECTOR TG
t \'Pe . C++ temp l ates prnv_ide a way t o r .e use. ·t he sou rce cod e a s oppo s ed to _h n.clude< i ostream.h> ' Ney,J ~1xro}(ft1 ~ --.,
(.,C/
inh e r i tan ce and compos1t 1on . .. ~ ~i nclude <conio . h> 'I::::,-- ~ -
( _A c1 .1 ss t emplate is highl U!2)Jli C~~l,i; i2...,.Y@S.fer the da ~a structur e and const i n t s ize =3; ~
.ilm_c; Uoru _f r om a. _p9 r_ent c l as s to_ th e· other .clas ses forming the st a n·dar-a. template <cla ss T> tx' ,
- s tru r· tur e . It is a l so i mpo r~a nt t o imp l ement inheritance i n ~ cl a s s vecto r ,"-l
• prog rammi r,q among the c la s s es . For e x amp le . a progr am to demon s tr ;, t e the
use o f t o.:mpla t e uses the intege:i;; fl oa t o r double ·in the s a me p rogranu.1in c
in ve cto r mul tipll ca tio_ n as . · ·
I private: :r *v ;T i ;
public : vecto r ( ) :~ · ~
(o/t'\
{ v ·.=;' Fl~'w T [ s i ze ] ; T i;
for (i=O.;'i / i ize~ :i:++)
/ ' WAP TO l MPLEMENT THE TEMPLATE CLASS in s ta ck
#inc lude <iostrearn . h>
,.):~·:<1p1l =O;

#i nc lude <conio . h> . :f.ect1,3r\ 'J.;; -..'a ) {T


i;
const int size=3; ~ ., .· . ./,: for(i~ O; i <s ize ; i++)
t empl ate <c} a ss T> ~ ;-\, ~[i] =a [i] ; ·
class stac k
( pri lfat e: T s tk [s i ze ];int t op; 'l' oper~E.sr·· ' <vecto r &y )
publi'c : s t ac k() { t op=-1 ; ) {T sum=O; i; ·
void push (T data) (t op++; s t k [ top ] =data; ) ,for (i=O ; i <s i ze; 1 ++)
T pop () { T data=stk [ top ] ; ' .sum+ =this - >v[i] •y .v [i] ;
top-- ; ret u rn data; } . ,. re turn sum ;
,,
int main(}
):;
~\.
- ~ ,,
{ clrscr() ; .i'.n t 'inain {)
(int x[3] = {1 , 3 , 2);

I
stack<1.0S 1;
sl .pu s h (lO); s l.pus h (20}; sl.pus h (30) ; int y[3] = {4,5,6) ;
veccor <int>vl ;
c out «sl. pop ( ) ; cout«sl. pop () ; cout « si. pop ( }';
ge t ch (}; .. v_e c ~or <int>v2;

J
ret urn O; I Vl"X;
v2" y; -
lll'rf 'R=v l *v2 ;
C1)Ut<< " \ n R::;: "<<R<< " \ n" i
/ /lvAP TO IM PLP.ME NT THE ~E'1PLA1'E c;etch(};
,. sta c k operat ion
return O;
(G 7J Prepared by Bh im Jhondari,
Oxford College of Engineering and Management [l' S] Prepar•id by Bhim Bhandari, Oxford College of Engineering and Mana gement
Radhabagale.Blogspot.Com

V~~-
K.lemplate Function
perform identical operations for . each
co nveniently, function t emplates are used.
data
type compactly
It provides_ a way
paramete ri ze the argument or return types. of a functi_on_. In
and
to
the
/
~ rmplementati.o n of f
.
# nclude<ios~ream. h>
#incl ude <conio. h>
#incl ude<ma th. h>
unctio
:.
n
t emplate to calculate quadrat i c r oo t

definition of the function, rather than specifying an expl~cit typ·e of cemplate <class T> ·
some of the argument or the return ,. value'. a placeholder is usect. Now
co nsider the following function which . will illustrate the Deed for 1 toot jT a,T b,T c)
{T d=b*b-4*a*c;
funct ion template. if{d==O)
voi d swap (int &x, int &y )
{ int temp ; {cout<<"Rl=R2="<<-b/ •
.else if (d>O) ( 2 a); I
temp=x;
x=y; {cout<<"\n Roots . are
T R=sqrt (·d); real \n "; ·
y=temp;
) . .
T Ri= (-b+R) / (2* a) ;
By using the above routine intef-' 2 . va lues can be_ -,s1:'appe;d: but for T R2=(-b-R)/(2*a);
fl oat and double numbers it needs to rewrite the code eit~er by ret. yr,ing <::out-1::<"Rl="<<Rl.
or copy and paste. It increases the code _length . r_n ·.':·a }t~r~ation, it can cout<<"\n R2="<~R 2 ,
be done by using the function overl_oadi_n g but in•··~~·~.~iple functions } '
def inition there is overhead of compila,tion and_. exe·eu:tion time. Thu else
func tion template provides a way to write a ~M};~,'!:,e function defini ti ~~ {cout<<"\n Roots are ,
where the-data type is in a parameter. For exaljlp.le·: . :· T Rl=-b/ ( 2*a); complex \n";
template <class T> T R2=sqrt (-ct); (Z*a) .
vo id swap (T &x, T &y) cout<<."\ n _Rea.1.
. '
part="«Rl;
{ T temp; . }cout« " \n Imagiriary part="«R2;
temp=x;
x=y;
y=temp; int rnain()
'I.' { :cout«"\n Integer coefficient .\.~:::{;\. . ·
Such fu nction is known as fun c t +~fr-:t~ci~late. ;·,~ ~~ '/.·"··.. rO_o t _(1, -5 ,.6 ). ; \ :/ . ::•_·,, ~-.
/\n ; cout«"\n Floating point c ~~{i e:i~~t \n";
I I WAP to Demonstra te the fun~U,qn - template by swapping values. ~;,l; ro.o t (L7,--,10.9,6.0J ; ,~ \ \
Ui nclude <iostream.h> fl) I get ch () · · ·, ,,'~-'1.~
#include <conio. h>
templa te <c lass T>
void swap(T &x, T &y f _
\'-' -~·
.' so: :
!J'.f, t""'" o, ·.. lr, r4:otf)}:
/T temp; t efJ:i"'.x';'.° •x~y; y=temp;)
void data (in t a, in t . ~, float m, float n) .
V ::Exc~PTIONHANouNG ) '-'.~ :,·•-:
An . lmportant f 1'( 11.\-i:e. _,of OOP that tracks the run time error then
/ cout«"('i;_n Va1ue of a and b ·before swap";
' '---t-Y·,
co ut ~<a<<","<<b ; te rminates the,,. co~~ (ll.Jt>d\:lle and trans)..ates into p. roper message. . .
cout<< " \n Value of m and n before swap'.' ;
fa simple, an ·J~J1ce1ftJ:on is a problem that a r ises . c;l.uring the execution of
al prtigrain. A,!¢p \,exception is a response to an exceptional circumstanc e
c.o ut<<m<< " , "<<n;
t hat·. arise s .' ~l1i·l ~· a program is running, such as an attempt to divide by
gc tch( h
zero. ~.x~eJ)tftin s provide a • way to transfer control from one part of a
prog r ani'i,to an6t her. C++ exception handling is built upon three keywo r ds:
cout<<"\ri\n Values after swap"; try , c~tlch; •: J nd t~row .
swap(a,b) ; i .. i lf.i:roi./: . ·;_ program thr~ws an exception when a problem shows up. Th i s
cou t « "\n Value of ,a and b after swap"; ,~!11,.,', s ' done tls1ng a thr.ow keyword ..
cout<<a << 11 , "<<b;
swap (m, n) ; 1 •
:.f{l,$1;Satch: A pr·)graro: catches ,m ,exception with ,a,n exception: handler at
· · ~i,,' the piace ·.in . •a program where you want to handle the problem.
cout«"\n Va lue of m and n after swap" ; The ca.tch keyword indicates the catching of an exception.
c out <~m<< 11 , ''<<n ; ii ..· tr::(: .A try · block identi.~iesa block ·of ·code for which particul ar
·exteptio·1s will be activated. ·· It's followed by · one . or more. catch
int main() blocks·: ·It · .a l.w ays works .as watchdog becau se error may occu r
{ clrscr{J; .anywhen, at any. time .
data (100, 200, 11.55, 33 . 88) ;
getch ( J ; ·
Assuming a block will raise an exception, a meth od catche s an
r et urn. O; · · · usinJ
· · a combin. ation Of the tr y and catch keywo r ds .
}
exception

[69/ Prepared by Bhim Bhonaari,


Oxford College of Engineering and Management Oxford College of Engineering and Management
[70) Prepared by fhim ~hondori,
A try ·catc h block is pl aced around the code t ha t mi ght ge ne r ate a n #in c lude <i ostrearn. h>
e xcept ion. Code wi th i n a try / ca t ch bl ock i s r e ferr ed t o as pro te cted iinclude <co nio , h>,
code, and the sy nt ax f o r us i ng tr y/catch l oo ks like t he f ol low ing: ,i ng nam~space s t d;
v uble division(int a, int b)
try d0
{ / / protected code
( if ( b == 0 . l 1

) ( t h row "Division by zero


return (a/b); conditi on' ";
ca t c h ( Except i onName el
( II catc h b l ock } ) '
catch ( Exce ptionName e2 j_nt ma i n ()
( II ca ~c h bloc k) ( in t X = 50;
ca tch ( Ex cep tionName eN i nt y = O;
( double z = O;
.l .'. -•
II c atch bl ock 'try {
.pl e ca t ch s tat eme n ts t o ca tch different. .:(Y.pe· of z · = division(x, y);
You ca n l is t dow n multl t r y bloc k r a ises more than Ol)~;_ .. .E!.xcept•ion . n cout << z << endl ;
1
e xcep ti ons in case your )catch (const char *rnsg)
di fferent si tuati ons . -}~---··
cerr << msg << endl;

b . i Thro wing Excepti ons : within a code , bl k return O;


Excep t i ons ca n be t hrown a nywhere , · o_c using \:hr.ow
the throw statements determines a type for th
l ope r an d Of
s tat e men t s . T1e ,. e
. t. d an be a ny expr ess ion and the type _ o,{ the result of th ~'.
exce p i on a n c . of exception thrown . . . ' . e Because we are raising an exception of type con s t ' char * so while
e xpress ion determines the type ·,f'';,._ • 'h ·
catchi ng this excepti on, we have to use const char;*. , in catch b l ock•
F~ll owing is an exampl e of throwing an exc_~-P,-~:;i;,~~ ---,w _en dividing by zero
co ndit i on occ urs: · ·;·\":· :, ·. If we compile and run above code, - this wo~ld produce the follow ing
do uble division{int a , int b l
. _r.esu l t : n'I, ,,;_1, .,, L., _
U.11v10 •1 '1] zero ~'?a-?tn
* "' -.
( i f ( b == 0 ) . I /wap to demonstrate ·the try and catch o·l .o ck ' fo·~ exception ha nd1 ing
( ·hnclude',iost;eam. h> ·, c.,· , •
th row " Div ision by ze ro cond i ~d.:ff .";
lli nclude <;conio. h>
} ::.~~~~~l• //using namespace std ;

}
r et urn (a/ b) ;
void -d1vide (int int y, int z) x,
b .i iCa tching Ex c epti ons : . . .
I
The ca t c h block fo llowing the · try block catches any exception. Y.ou can cout«"\n we are i nside the;.i;nction " ;
specify what type of exceptib i:i yo u want to catch and thi s is determined - ~f( (~ttO) . / ~i}:~~~ .
by
th e exceptio n
.
de cl arat i on · that a ppears in parentheses following th e
r-z/ (x- y) ; '<'.~\ .-.,.
1
cout<<"resu it=' · !;.:''·:' .
keywo rd ca tch .
try e l se
( )
/ ,' pro tected • code·
·.,'- ·.~.:
voidmain() · •~- , ·
~"-\:
( try . ..· ~.~!
catch( ExceptionName e) ( ·, cout'<>:: " \n we are ins ide the try bloc k \n" ;
{ i:. _s{f·.'.\:-
divide ( 10 , 1.0 , 30) ;
// code, to ha ndl e E:,cepti onN ame except ion -~.\.,,_: ,; . divide(l0,10, 20 ) ;
./''i},~-
Above. f ode will c atch an excep ti on of Excep t ion Name type . If you wa nt t o . ~~ ~
c a~:¢~,tt,rt )
!

speci,fy that a catc h block s houl d ha ndl e a ny type of exce p tio n tha t i s · .{:_ ·;lc otit« "\n cout the exception ";
th r bV/h in a tr y block , you mu s t put . a n e llips i s, b etwee n Lhe ge { gi{ o;
pa re nth eses enc l os inf t he exceptio n de claratio n as follows : )
try
{
// protec ted code
}catch( ... )
{
II code t o hand le any exceptio n Radhabagale.Blogspot.Com
The follo wi ng is <1 11 ·exampl e, whi ch t h rows a division by zero e xception
and 1,•e catch it in catch block.
Oxford College of Engineering and Management
(71) Prepared by Bh im Bhmdori, Oxford Coll ege of Engineerin g and Management [n] Pre pared bv Bhim Bhanddri,
4.4 Implement the following diagram for multilevel-
multiple inheritances.

STAFF
Id, name
Readdata(), displaydata()

FULLTIME LECTURER
Post Sub, depart
Readdata3(), displaydata3() Readdatal(), displaydatal()
Assignment· lmplem t th f II . . : .
· en e o owing hierarchy by assuming read and·· show functions
1
PARTTIME
. ~-- 2. member academic
lntinie, outtime, totalhour College
Readdata2(), displaydata2{)
Name

\.... ,,,_ ,.· faculty


,..__....;...__.,.., :·,,.;··

4.5 WAP to implement the h)~:, ______ . nheritance Studl!nt k ~,c.her


~, • ' - I

Name stude nt
.,=,~N am:e
class FULLTIME : publ ic ~T.A~( l ECTURER ' ~\'..1 ~,.(
·name
. Roll no 1
. • ~-<,:·ode
.<.:!;~-~ \:--. :-~·.- - - ~
STAFF r..:.3..._·c...
_ - k---'-:.,_.::~
; , ,~
.; •J, ,i
test
Id, name sub, dept B oo,ts. v·. ,, - sport
. . ,F/~~'-
Readdata(), displaydata() Readdatal(), displaydatal() Mit k?
. . ~~~(''''.
e ,{a:
:-~~- ~ ¼le
. ~ ~;ite'i name result
.-. -. .~ r?- ;\:>. -
'::; :_ · Code
post i;,~'\ : ...\.".,.:t) ,__...;;__ __ .:...J

Readdata2(), displaydata2() - a) ~~ ~~~~i i: n ir1stitute wishes to maintain a data.base of its employees. The
la:a·t~oa'-Ve is, divided into a number of classes _whose hierarchical relationships are
; fiq~-n in figu re. The figure also shows the minimum information required for each
class. Specify. all the classes and define functions to create the database and
retrieve individiJai information as an when required .

4.6 WAP to implement the hybrid Inheritance


/ _ _---=
Sc.:.:
TA .::. F --__.j
F.:.._

r- Id, name
(73 ) Prepa re d by [ Rea ddata(), dis p\aydata(l Oxford College of Engineering ;rnd Mana ge ment
Oxfo rd Coll ege of Engineering and Management [74 ] Prepared by Bhim i,handari,
d. WAP to implement th M .
. e ult1ple Inh eritan ce

person r--- -_ _ ::.STAFF


n a 111 e
co d e
\
,--___ Id, name
Readdata() d"5
' ' Plavdata()
I

~d~
'
account
ad m in I Readdatal() .
experience
' disp/aydatal()
pay

· person
speed

perso·.n
person
spe e d

· a) What is multiple inheritance? Does_ ambiguity


s p ··e e _d·

5. WAPto imple
ment the hyb .d I .
~
~ J 'l (:S
AM
n nhentance
occurs in this type of inheritan~~7Jf yes, explain
with a.n example. ··
a) Th~ follc"'·ing tigun: shuws minimum inforinatio'.1 required for each class. Write a
prngr:un with member timctions to read. and ~hsplay information of individual Id, name
object. Every class should contain a~ l~a?t'one constructor and should be inherited
tu oilier cb;ses 35 well. · •· ·

----
LECTURER()
LECTURER
Sub, dep_a_rt- - ,
.
, d1splayda ta()

.<\DMJN
lntime o u ~
' inie, totalhour

ll.[•·vl lNi-) j" -

l1 nµle1nent the foll


owing h1erarch b
0 AM -5
.:- t IS!)lu·1datc110

J
c y y assun1ing read d
N
" , r ' "
-
' an show fu nc t ions
,I Ill L'

b) Explain and contrast the following:


i. lS-A-rule N ,t fl) ('

\i. 1-IAS-A-ru\e (' 0 i.J I'

3. Develop a c0mplete program for an institution which wishes to maintain


a database of its staff. Declare a base class STAFF which include
sraff_id and name. Now develop records for the follo'iving staffs with the 1 r 111·

('
I

,, d
11

l'
.! l:l l' j
~
giwn information below:
/Ii]
Prepared by 6/im, Bh ondari,
·-c. PreoJ red b· qh'm Bhandari Oxford College of Engineeri ng and Managerne" 1
C:iford Colle e f
g . o Engrn ee n ng and M
. .
an°ern1 cnt

Вам также может понравиться