Docsity

Cse iii object oriented programming with c [10cs36] notes, Exercises of Computer Science

Toggle sidebar
bg1
++C htiw gnimmergorP detneirO tcejbO 63SC01
TIBJS๎˜ƒ,ESC๎˜ƒfo๎˜ƒ.tpeD ๎˜ƒ๎˜ƒ
SYLLABUS
TCEJBO DETNEIRO PGNIMMARGOR HTIW ++C
moC( mno to ESC & )ESI
tcejbuS :edoC 01 C 63S 52 : skraM .A.I
uoH r W/s e ke : 40 30 :sruoH maxE
latoT uoH rs : 25 001 :skraM maxE
PTRA โ€“ A
U TIN 1
tcudortnI ion: weivrevO fo ,++C elpmaS ++C ,margorp tnereffiD atad
to,sepyp ,srotare ex,snoisserp dna ,stnemetats rraasy dna irts ngs, sretniop &
denifedresu tsepy noitcnuF ,stnenopmoC ragtnemu nissap g, enilni ,snoitcnuf
noitcnuf nidaolrevo g, evisrucer snoitcnuf
U TIN 2
sessalC & stcejbO โ€“ :I ssalC ,noitacificepS ssalC ,stcejbO epocS noituloser
,rotarepo sseccA m ,srebme ifeDngni me bm er ,snoitcnuf ataD ,gnidih
tcurtsnoC o,sr rotcurtseD ,s deziretemaraP ,srotcurtsnoc citatS atad me ebm r ,s
Fnu c snoit
U 3 TIN
sessalC & stcejbO โ€“:II dneirF ,snoitcnuf gnissaP stcejbo sa ar ,stnemug
gninruteR ,stcejbo rrAasy fo ,stcejbo Dcimany ,stcejbo sretnioP ot ,stcejbo
oC py oc n ,srotcurts eG n cire snoitcnuf snoitacilppA ,sessalc dna rotarepO
gnidaolrevo gnisu snoitcnuf dneirf hcus ,+ sa - erp, - ,tnemercni tsop - ,tnemercni ] [
idaolrevo ,.cte ng ,<< >>.
www.rejinpaul.com
www.rejinpaul.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Cse iii object oriented programming with c [10cs36] notes and more Exercises Computer Science in PDF only on Docsity!

Ob jectOrientedProgremmingwithC++ 10 CS 36 Dept.ofCSE,SJBI T

SYLLABUS

OB JEC TOR IENTEDP RO GRAMMINGWI THC++

(C o mm on to CS E& ISE) Su bjec tCo de: 10 C S 3 6 I.A.Marks: 25 Ho ur s/ We ek : 04 ExamHours: 03 To ta lHo urs : 52 ExamMarks: 100 P AR Tโ€“ A U NI T 1 In troduc tion: Ov erview of C+ +, Sa mple C+ + pr ogram, Di fferent data t yp es,op er ators, ex pr essions, an d st atements, ar ra ys an d st rings, po inters & us erdefine d t yp es Fu nction Co mponents, ar g um ent pa ssing, in line functions, fu nctio nov erloading, re cursivefunctions U NI T 2 Cl asse s & Ob jects โ€“ I: Cl ass Sp ecification, Cl ass Ob jects, Sc ope resolution op erator , Ac cess m em bers, De fin in g me mb er fu nctions, Da ta hiding, Co nstruc to rs , De structor s, Pa rameterized co nstructors, St atic da ta me mb er s, F un c tions U NIT 3 Cl asse s & Ob jects โ€“ II : Fr iend fu nctions, Pa ssing ob jects as ar guments, Re turnin gob jects,Ar ra ys of ob jects, D yn amic ob jects, Po inters to objects, C o py co n st ructors, Ge n er ic fu nctions an d classes, Applications Operator ov erloadin gus ingfr iendfunctionssu chas +,- ,p re- in crement,po st- in crement,[] et c.,overload ing << ,>>.

Ob jectOrientedProgremmingwithC++ 10 CS 36 Dept.ofCSE,SJBI T

U NI T 4

I n h er itance โ€“ I: Ba se Cl ass, In heritance an d pr otected me mbers, Pr o tected b a se cl assin heritance,I nh eritingmu ltipleba se cla sses PART โ€“ B U NI T 5 I n h er itance โ€“ II : Co ns tr uctors, De structors and In he ri tan ce , Pa ssin g p ar ametersto ba se cl assco nstructors,Gr antingac ce ss ,Vi r tu al base cl a sses U NI T 6 Vi rtua l f un ctions, Po lymo rp hism: Vi rt ual fu n ct ion,Ca llinga Vi rtual fu ncti on t hr ough a ba se cl as s re feren ce , Vi r tu al at tribute is in herited, Vi rtual fu nc ti ons ar e hi erar ch ical, Pure vi rtualfu nctions,Ab stractcl asses,Us ingvi rtualfunctions, E ar ly an dla te binding. U NI T 7 I/ O Sy stem Ba sics, Fi le I/ 0 : C+ + st ream cl asses, Fo rmatted I/ O, I/O m an i pu lators,fs treaman dth eF il ecla ss e s, F il eop er ations U NI T 8 Ex ceptio n Ha ndling, ST L: Ex ce ption ha ndling fu ndamentals, Ex ception ha ndlin gop tionsST L: An ov erview,co ntainer s, v ec to rs,lists. Te x tBooks:

  1. He rbertSc hildt:Th eCo mpleteRe f er ence C+ + , 4 thEd ition,Ta taMc G ra wH ill,

Re ferenc eBooks:

  1. St anleyB.Li p pmann,Jo seeL aj ore:C+ +Pr imer, 4 thEd ition,Pe arsonEd uca tion,
  2. Pa ulJDeitel,Ha rveyM De itel:C+ +fo rPr og ra mmers,Pe arsonEd uca ti on, 2009.
  3. K R Ve nu go pal,Ra jk um arBu yy a,T Ra viSh ankar:M as tering C+ +.

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 1

UNIT I

INTRODUCTIO N

Topicscovere d In troduction : Overview of C++, Sample C++ program, Different data types, operators,expressions,andstatements,arraysandstrings,pointers&userdefinedtype s Fu nctionComponents,argumentpassing,inlinefunctio ns,functionoverloading,recursive function s UN I T- 1 Summary TounderstandC++istounderstandtheforcesthatdroveitscreation,theideastha t shapedit,andthelegacyitinherits.Thus,thestoryofC++beginswithC.Thischapte r pr esents an over view of the C programming language, its origins, its uses, and its underlyingphilosophy.BecauseC++isbuiltuponC,thischapterprovidesanimportan t historicalperspective on the rootsof C++.Much ofwhat โ€œmakesC++,C++โ€hadit s ge nesisintheClan guage

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 2 1. OverviewofC++ C++beganasanexpandedversionofC.TheC++extensionswerefirstinvente d byBjarneStroustrupin 1979 atBellLaboratoriesinMurrayHill,NewJersey. He initiallycalledthenewlanguage"CwithClasses."However ,in 1983 the namewaschangedtoC++.AlthoughCwasoneofthemostlikedandwidel y usedprofessionalprogramminglanguagesintheworld,theinventionofC+ + wasnecessitatedbyonemajorprogrammingfactor:increasingcomplexity. 2. SampleC++program A SampleC++Program Let'sstartwiththeshortsampleC++programshownhere. #include intmain( ) { inti ; co ut<<"Thisisoutput .\ n"; //thisisasinglelinecomment /youcanstilluseCstylecomments / //inputanumberusing> > co ut< <"Enteranumber:"; cin>>i ; //now,outputanumberusing< < co ut<<i<<"squaredis"<<i*i<< "\ n"; return 0 ; } 3. Differentdatatypes

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 4 co nverte dto th ety peof th ele ftsi de(t arget va riable),as il lustratedhere: Ta ble 2 - 3 summarizestheassignmenttypeconversions.Rememberthattheconversion of a n in t to a fl oat , ora fl oat to a do uble ,andsoon,doesnotaddanyprecisionor ac curacy. These kinds of conversionsonly change the form in which the value is re presented.Inaddition,somecompilersalwaystreat a ch ar variableaspositive,no ma tterwhatvalueithas,whenconvertingittoa n in t or fl oat. Othercompilerstreat char va riablevaluesgreaterthan 127 asnegativenu mberswhenconverting.Generally Ta r getT yp e Ex pressionTy pe Po ssibleIn foLoss s igne dc har ch ar If va lue> 12 7 ,ta rgetis negative ch a r s hortin t Hi gh- order 8 bits ch a r in t( 1 6 bi ts) Hi gh- order 8 bits ch a r in t( 3 2 bi ts) Hi gh- or der 24 bits ch a r lo ngin t Hi gh- or der 24 bits s hor tin t in t( 1 6 bi ts) None s hor tin t in t( 3 2 bi ts) Hi gh- or der 16 bits in t( 1 6 bi ts) lo ngin t Hi gh- or der 16 bits in t( 3 2 bi ts) lo ngin t None i n t fl oat Fr actionalp artan dpo ssiblymore fl oa t do uble Pr ecision,resultrounded d o ub le lo ngdo uble Pr ecision,resultrounded Ta bl e 2 - 3. Th eOu tcomeof Co mmonTy peConversion 4. 3 MultipleAssignment s C/C++ allows you to assign many variables the same value by using multipl e as signmentsinasinglestatement.Forexample,thisprogra mfr agmentassigns x , y , and z thevalue 0 : x=y=z= 0 ;Inprofessionalprograms,variablesarefrequentlyassignedcommonvalue s usingthismethod. 4. 4 ArithmeticOperator s Ta ble 2 - 4 listsC/C++'sarithmeticoperators.

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 5 4. 5 IncrementandDecremen t C/ C++includes twouseful operators not foundinsome other computer languages. Th esearetheincrementanddecrementoperators , ++ an d- -. Theoperator ++ adds 1 to it soperand,an d- - subtracts 1 .Inotherwords: i s th esa meas an d **4. 6 Relationa la nd Lo gicalOperators

  1. 7 Bitwis eOperators**

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 7 ho l d. F or ex ample,to de clarean ar ray st r th atca nho lda 10 - ch aracterstring, yo uwo uldwr iteTh isma kesro omfo rth enu llat th een dof th estring. Wh e nyo uus ea qu otedst ringco nstantin yo urpr ogram,yo uar eal socreating a nu ll- te rminated st ri ng. A s tring co nstant is a li st of ch aracters en closed in do ubl equ otes.Fo rexample, "h ell o th ere" Yo^ u do^ no^ t ne^ ed to^ ad^ d th^ e nu^ ll to^ th^ e en^ d of^ st^ ring constants ma nuall yโ€” th eco mpilerdoesthisforyouautomatically. C/ C+ + su pports a wi de ra nge of fu nctio ns th at ma nipulate nu ll-t erminated strings. Th emo stco mmonare Na m e Function s t r cp y( s 1 , s 2 ) Co pies s 2 in to s 1. s t r ca t( s 1 , s 2 ) Co ncatenates s 2 on toth een dof s 1. st rle n( s 1 ) R eturnsth ele ngthof s 1. s t r c mp( s 1 , s 2 ) Re turns 0 if s 1 an d s 2 ar eth esa me;le ss than 0 if s 1 < s 2 ; gr eaterthan 0 if s 1 > s 2. s t r ch r( s 1 , ch ) Re turnsa po interto th efi rstoc currenceof c h in s 1. st rst r( s 1 , s 2 ) Re turnsa po interto th efi rstoc currenceof s 2 in s 1. Th es efu nctionsus eth est andardhe aderfi le st ring.h. (C ++pr ograms ca nal souse th eC+ +- st yle he ader .) Th efo llowingpr ogramil lustratesth eus eof th es est ringfunctions: 5. 2 Tw o- Di mensionalArrays C/ C+ + su pports mu ltidimensional ar rays. Th e si mplest fo rm of the mu ltidimensiona lar rayisthetwo- di mensionalarr ay. A tw o- di mensionalarray is , es sentially, an array of on e- di mensional ar rays. To declare a two- di mensionalintegerarra y d of si ze 10 , 20 ,yo uwo uldwrite in td[ 10 ][ 20 ]; Pa y ca refulat tention to th e de claration. So me ot her co mputerla nguages use co mma s to se parate th e ar ray di mensions; C/ C++, in co ntrast, pl aces each di mensio nin it s ow nse tof br ackets.Si milarly, toaccesspoint 1 , 2 ofarray d , yo uwo ulduse

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 8 Tw o- di mensional ar rays ar e st ored in a row- c olumn matrix, where the first in dexindicate sth ero wa ndth ese condin dicates t he co lumn. Th is me ansthat th e ri ghtmost index ch anges fa ster th an th e le ftmost wh en ac cessing the el ement sin t hear rayin theor derin wh ichth eyar eac tuallyst oredin me mory. In th e ca se of a tw o- di mensional ar ray, th e fo llowing f ormula yi elds the nu mbe rof by tesof me moryne ededto ho ldit: by te s= si zeof 1 s tin dexx si zeof 2 n din dexx si zeof(basetype) Th erefore , as suming 4 - by te in tegers, an in teger ar ray wi th di mensions 10 , 5 wo ul dhave 10 x 5 x 4 o r 20 0 by tesallocated. 5. 3 Multidimensiona lArrays C/ C+ +al lows ar rays of mo re th antw odi mensions. Th eexactlimit,if any ,is de termine d by yourcompiler. Th e ge neralfo rmof a mu ltidimensional array de claratio nis ty p ena me [ Si ze 1 ][ Si ze 2 ][ S ize 3 ].. .[ Si zeN ]; Ar ray s of mo re th an th ree di mensions ar e no t of ten us ed be cause of the am ount o f me mory th ey re quire. Fo r ex ample, a fo ur- di mensional character ar ra ywi thdi mensions 10 , 6 , 9 , 4 requires 10 * 6 * 9 * 4 o r 2 , 160 by tes. If th ear ra yhe ld 2 - by tein tegers, 4 , 320 by tesw ouldbe ne eded. If th ea rrayhe ld do uble s (a ssuming 8 by tespe r do uble ), 17 , 280 byteswouldbe re qu ir ed. Th es torage re quiredin creasesex ponentiallywi thth enu mberof di mensions. Fo rex ample,ifafifthdimensionofsi ze 10 wasaddedtotheprecedingarray, th en 172 , 80 0 by teswo uldbe required. In mu ltidimensional ar rays, it ta kes th e co mputer ti me to co mpute ea ch i ndex. Th i s me ans th at a ccessing an el ement in a mu ltidimensional ar ray ca n be sl owe rth ana ccessingan el ementin a si ngle- di mensionarray. 6. Pointers&userdefinedtypes Th e co rrect un derstanding an d us e o f po inters is cr itical to successful C/ C+ + pr ogramming. Th ere ar e t hree re asons fo r th is: F irst, pointers pr ovid eth eme ansbyw hichfu nctionsc anm odify th eirca llinga rguments. Se cond , po inters su pport dy namic al location. Th ird, po inters ca nimprove th eef ficiencyof ce rtainro utines. Al so,as yo uwi llse ein Pa rtTw o,pointers ta k eon ad ditionalro lesin C+ +.Po inters a re o ne of th e st r on gest bu t a lso o n e of t he mo st da nger o us fe atures in C/ C ++. Fo r e xample, un initialized po inters (o r po inters co ntaining in val id va lues) ca n c ause yo ur s ystem to cr ash. Pe r ha ps wo rse, it is ea sy to u s e po inters in corr ec tly, ca usingbu gsth atar everydifficulttofind.B ecause

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 10 i s in itializedby th ev alueof i an dv 2 by th evalueof j. 7. 2 Functio nBo dyIs a Scope Th ebo dyof a fu nctionis a st atementbl ock,wh ichde finesth efu nction'sop eration.As us ual ,th eblockis en closedby a pa irof cu rlybr acesan dhe ncefo rmsa ne wsc ope.As wi t han ybl ock, th e bodyof a fu nction ca n de fine va riables.Namesde fined in side a fu nctio nbo dyar eac cessibleonlywi thinth efu nctionit self.Su chva riablesar ere ferredto a s lo calva riables. Th eyar e"local"to th atfu nction;th eirna mesar evi sibleon lyin the sc op e of th e fu nction. They ex ist on ly while th e fu nction is ex ecuting. Execution co mplete swh ena re turn st atementis en countered.Wh enth eca lledfu nct ionfinishes,it yi eld sas it sre sultth eva luesp ecifiedin th ere turn st atement.A fterth ere turnis executed, th esu spended,ca llingfu nctionre sumesex ecutionat th epo intof th eca ll.It us esthe re turn valu e as th e re sult of ev aluating th e ca ll op erat or an d co ntinues processing wh ateve rre mainsof thest atementin wh ichth eca llwa sperformed. 7. 3 Parameter san dArguments Li k elo calva riables,th epa rametersof a fu nctionpr ovidena med,lo calst oragefo rus eby th efuncti on. Th edi fferenceis th atpa rametersar ede finedin sideth efu nction'sparameter li s tan darein itializedby ar gumentspa ssedto t hefu nctionwh enth efu nctionis called. A n ar gumentis an ex pression.It mi ghtbe a va riable,a li teralco nstantor an expression in volvin gon eor mo reop erators.Wemu stpa ssex actlyth esa menu mberof ar gumentsas th efunctio nha spa rameters.Th et ypeof ea char gumentmu stma tchth ecorresponding pa rameteri nth esa mew ayth atth ety peof an in itializermu stma tchth ety peof th eobject i t in itializes:Th ear gumentmu stha veth esa met ypeor ha vea ty peth atca nbe implicitly converte d 7. 3 Functio nRe turnType Th ere turnty peof a fu nctionca nbe a bu ilt- in ty pe,su chas in t or do uble , a cl asstype, o r a compoundty pe,su chas in t& or st ring. A re tu rnty peal soca nbe vo id , which me an sth atth efunctiondo esno tre turna va lue.Th efo llowingar eex ampledefinitions o f po ssiblefu nctionretu rn ty pe s: bo o lis _present(int, in t); // re turns bool in tco unt(constst ring&, ch ar); // re turns int Da t e& ca lendar(constch ar); // re turnsre ferenceto Date vo i dpr ocess(); // pr ocess do esno tre turna value A fu nction ma y no t re turn an other fu nction or a bu ilt- in ar ray ty pe. In stead, the fu nctio nma yreturna po interto th efu nctionor t oa po interto an el eme ntin th earray: / / ok :po interto fi rstel ementof th earray in tf oo_bar(){ /* .. .*/ } Th i sfu nctionre turnsa po interto in t an dth atpo interco uldpo int to an el ementin an array.

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 11 7. 4 Function sMu stSp ecifya Re turnType I t is il legalto de fineor de clarea fu nctionwi thoutan ex plicitre turntype: / / er ror:mi ssingre turntype te st(doubl ev 1 ,do ublev 2 ){ /* .. ./ } Ea rile rve rsionsof C+ +wo uldac ceptth ispr ograman dim plicitlyde fineth ere turntype o f te stas an in t. Un derSt andardC+ +,th ispr ogramis an error. 7. 5 Functio nPa rameterList Th epa rameterli stof a fu nctionca nbe em ptybu tca nnotbe om itted.Afu nctionwi thno pa rameter s ca n be wr itten ei ther wi th an em pty p arameter li st or a pa rameter list co ntainin gth esingleke ywordvo id. Fo rex ample,th efo llowingde clarationsof process ar eequivalent: vo i dpr ocess(){ / .. ./ } // im plicitvo idpa rameterlist vo i dpr ocess(void){/ .. ./ } // eq uivalentdeclaration A pa rameterli stco nsistsof a co mma- se paratedli stof pa rameter ty pesan d(optional) pa ramete rna mes.Evenwh enth ety pesof tw op arametersar eth esa me,th ety pemu stbe repeated : in tma nip(intv 1 ,v 2 ){ / .. ./ } // error in tma nip(intv 1 ,in tv 2 ){ / .. ./ } // ok N o tw opa rametersca nha veth esa mena me.Si milarly,a va riablelo calto a fu nctionmay no t us e th e sa me na me as th e na me of an yof th e fu nction'spa rameters. Names are op tional ,bu tin a fu nctionde finition,no rmallyal lpa rametersar ena med.A parameter mu s tbe na medto be used. 7. 6 Paramete r T yp e- Checking Wh e nwe ca lla fu nction,th et ypeof ea char gumentmu stbe ei therth esa mety peas the co rrespondin gpa rameteror a ty peth atca nbe co nvertedto th attype. Th efu nction'spa rameterli stpr ovidesth eco mpilerwi thth ety pein formationne ededto ch eckth ear guments.Fo rex ample,th efu nctiongc d , wh ichw ede finedon pa ge 22 6 , ta ke stw oparametersof ty pein t : gc d("hello" ,"w orld");// er ror:w rongar gumenttypes gc d( 24312 ); // er ror:to ofe warguments gc d( 42 , 10 , 0 ) ; / / er ror:to oma nyar guments Ea c hof t heseca llsis a co mpile- ti meer ror.In th efi rstca ll,th ear gumentsar eof type co nstcha r. Th ereis no co nversionfr omco nstch ar*toin t , so th eca llis il legal.In the se con dan dth irdca lls,gc d is pa ssedth ewr ongnu mberof ar guments.Th efu nctionmust b e ca lledwi thtw oar guments;it is an er rorto ca llit wi than yot hernumber. Bu twh atha ppensif th eca llsu ppliestw oar gumentsof ty pedo uble? Is th isca lllegal?

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 13 no nreferenc ety pepa rameter,ch angesma deto th epa rameterar ema deto thelo calcopy. I f th efu nc tionas signsa ne wpo interva lueto th epa rameter,th eca llingpo intervalueis unchanged. vo i dre set(int*ip) i p= 0 ; // ch angesth eva lueof th eob jectto wh ichip points i p = 0 ; // ch angeson lyth elo calva lueof ip; th ear gumentis unchanged } A ft era ca llto r eset , th ear gumentis un changedbu tth eob jectto wh ichth eargument po intswil lbe 0 : in ti = 42 ; in tp = &i; co u t<< "i :" << p << '\ n' ; // pr ints i: 42 re set(p ); // ch anges *p bu tno tp co u t<< "i :" << p << en dl; // ok :printsi: 0 I f we wa nt to pr event ch anges to th e va lue to wh ich th e po inter po ints, th en the pa rametershoul dbe de finedas a po interto co nst : vo i dus e_ptr(constin tp) { / / us e_ptr ma yre adbu tno twr iteto *p } Wh ethe ra po interpa rameterpo intsto a co nst or no n co nst ty peaf fectsth earguments th a twe canus eto ca llth efu nction.W eca nca llus e_ptron ei theran in t* or aconst in t * ; we ca n pa ss only on an i nt* to r eset. This di stinction fo llows fr om the in itializatio n ru les fo r po inters. We ma y in itialize a po inter to co nst t o po int to a n o n co nst ob jectbu tmayno tus ea po interto no nco nst to po intto aco nst o bject. 8. 3 con st Parameters W e ca nca lla fu nctionth atta kesa no nreference,no nco nst pa rameterpa ssingei thera co n st or non co nst ar gument.Fo rex ample,we co uldpa sstw oco nstin t s to ou rgc d function : co ns ti nti = 3 , j = 6 ; in tk = rg cd( 3 , 6 ) ; // ok : k in itializedto 3 Th i sbe haviorfo llowsfr omth eno rmalin itializationru lesfo rco nst ob jects.Because th ein itializationco piesth eva lueof th ein itializer,we ca nin itializea no nco nst object fr o ma co nst ob ject,or vi ceve rsa.Ifwe ma keth epa rametera co nst nonreference type : vo i dfc n(constin ti) { / fcn ca nre adbu tno twr iteto i */ (^) th enth efu nctioncannot ch ang eit slo calco pyof th ear gument.Thear gumentis st illpa ssedas

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 14 a co pyso we c anpa ssfc n ei thera co nst or no n co nst ob je ct. Wh a tma ybe su rprising,is t hatal thought hepa rameteris a co nst in sideth efunction, th ecompile rot herwisetr eatsth ede finitionof fc n as if we ha dd efinedth eparameter a s a pl ainin t: vo i dfc n(constin ti) { /* fcn ca nre adbu tno twr iteto i / } vo i dfc n(inti) { / .. .*/ } // er ror:re defines f cn (int) Th i sus age ex iststo su pport co mpatibilitywi thth e C la nguage, wh ich ma kesno di stincti on betweenfu nctionsta kingco nst or no n co nst parameters. Li mitation sof Co pyingArguments Co pyin gan ar gumentis no tsu itablefo rev erys ituation.Ca seswh ereco pyingdoesn't wor k include : Wh e nwe wa ntth efu nctionto be ab leto ch angeth eva lueof an ar gument. Wh e nwe wa ntto pa ssa la rgeob jectas an ar gument.Th eti mean dsp aceco ststo copy th eob jectar eof tento ohi ghfo rr eal- wo rldapplications. Wh e n th ere is no wa yto co py th e ob ject. In th ese ca seswe ca n in steadde fine the pa rameter sas re fere ncesor pointers. 8. 4 Referenc e Parameters A s an ex ampleof a si tuation wh ere co pyingth e ar gumentdo esn'two rk, co nsider a fu nctio nto sw a pth eva luesof it stw oarguments: / / in correctve rsionof sw ap: Th ear gumentsar eno tchanged! vo i dsw ap(intv 1 , in tv 2 ) { in ttm p= v 2 ; v 2 = v 1 ; // as signsne wva lueto lo calco pyof th eargument v 1 = tmp; } // lo calob jectsv 1 an d v 2 no lo ngerexist I n th isca se,we wa nt to ch angeth ear gumentsth emselves.As de fined,th ough,sw ap ca nnotaffec tth osear guments. Wh enit ex ecutes,sw ap ex changesth e lo calco pies of it sar guments. Th eargumentspa ssedto sw ap ar eunchanged: in tmain()

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 16 We ' dal soli keth efu nctionto returnan oc currenceco untif th eva lueoc cursmo rethan on ce .In th isca seth eit eratorre turnedshouldbe to th efi rstel ementth atha sth evalue fo rwh ichwe 'relo oking.Howca nwe de finea fu nctio nth atre turnsbo than it eratorand a n oc currenceco unt?We co ulddefinea ne wty peth atco ntainsan it eratoran da count. A n ea sierso lutionis to pa ssan additionalre ferencear gumentth atfi nd_val ca nus eto re tur na co untof th enu mberof occurrences: / / re turnsan it eratorth atre fersto th efi rstoc currenceof value / / th ere ferencepa rameter oc curs co ntainsa se condre turnvalue ve ctor::const_iterato rfind_val( ve ctor::const_iterato rbe g, // fi rstelement ve ctor::const_iterato ren d, // on epa stla stelement in tva lue, // th eva luewe want ve ctor::size_typ e&o ccurs) // nu mberof ti mesi toccurs { / / _r es iter wi llho ldfi rstoc currence,if any ve ctor::const_iterato rre s_iter= end; oc cur s= 0 ; // se toc currenceco untpa rameter fo r( ; be g!= en d;++beg) i f (* beg== va lue){ / / re memberfi rstoc currenceof value i f (r es_iter== en d)re s_iter= beg; ++ occurs ;// in crementoc currencecount } re tur nre s_iter; // co untr eturnedim plicitlyin occurs } Wh e nwe ca llfi nd_val , we ha ve to pa ssfo urar guments:a pa irof it eratorsth atdenote th e rang e of el ementsi nth e ve ctor in wh ich to lo ok, th e va lue to lo okfo r, and a si ze_ty pe) ob jectto ho ldth eoc currenceco unt. As sumingiv ec is a vector,it is an it erato rof th eri ghtty pe, an dct r is a si ze_type , we co uldca llfi nd_valas follows: i t = fi nd_val(ivec.begin(),i vec.end(), 42 ,ctr); Af te rth eca ll,th eva lueof ct r wi llbe th enu mberof ti mes 42 oc curs,an dit wi llrefer t o th efirstoc currenceif th ereis on e. Ot herwise,it wi llbe eq ualto iv ec.end()and c t r wi llbe zero. 8. 6 Usin g( co nst ) Re ferencesto Av oidCopies Th e ot her ci rcumstance in wh ich re ference pa rametersar e us eful is wh en pa ssinga la rg eob jecttoa fu nction.Althoughco pyingan ar gumentis ok ayfo rob ject sof bu ilt- in da t aty pesan dfo robjectsof cl asst ypesth atar esm allin si ze,it is (o ften)to oinefficient fo r ob jectsof mo st cl asstypesor la rge ar rays. By us inga re ference pa rameter, the fu nctio nca nac cessth eob jectdi rectlywi thoutcopy in git .As an ex ample,we 'llwr itea fu nctio nth atco mparesth ele ngthof tw os tring s. Su cha fu nctionneedsto ac cessthe si ze of ea chst ring bu tha sno ne edto wr iteto th est ring s. Be causest ring s ca nbe long,

Ob jectOrientedProgrammingwithC++ 10 CS 36 De pt.ofISE,SJBI T Pa ge 17 we ' dli keto av oidco pyingt hem.Usingco nst re fe renceswe ca nav oidthecopy: / / co mparet hel engthof tw ostrings bo o lis Shorter(constst ring&s 1 ,co nstst ring&s 2 ) { re tur ns 1 .size()< s 2 .size(); } Ea c hpa rameteris a re ferenceto co nstst ring. Be causeth epa rametersar ere ferencesthe ar gument sar e no tco pied.Be causeth epa rametersar ec onst re ferences,isSh ortermay no tus eth ere ferencesto ch angeth earguments. 8. 7 Pa ssinga Re ferenceto a Pointer Su ppos ewe wa ntto wr itea fu nctionth atsw apstw opo inters,si milarto th epr ogramwe wr oteear li erth atsw apstw oin tegers.We kn owth atwe us e* to de finea po inter an d& t o de finea reference. Thequ estionhe reis ho wto co mbineth eseop eratorsto ob taina re ferenc eto a pointer. He reis an example: / / sw apva luesof tw opo intersto int vo i dpt rswa p(int& v 1 ,in t&v 2 ) { in tt mp= v 2 ; v 2 = v 1 ; v 1 = tmp; } Th epa rameterin^ t&^ v^1 sh ouldbe re adfr omri ghtto le ft:v 1 is a re ferenceto a po interto a n ob jecto fty pein t. Th atis ,v 1 is ju stan otherna mefo rwh ateverpo interis pa ssedto pt rsw ap. We co uldre writeth em ain fu nctionfr ompa ge 23 3 to us ept rswap an dswap po inter sto t heva lues 10 an d 20 : in tmain() { in ti = 10 ; in tj = 20 ; in tp i= &i ; // pi po intsto i in tp j= &j ;// pj po intsto j co u t<< "B eforept rswap():\ t* pi:" < < p i<< "\ t pj:" << p j<< endl; pt rswap(pi ,pj );// no w pi po intstoj; pj po intstoi co u t<< "A fterpt rswap():\ t pi:" < < p i<< "\ t pj:" << *p j<< endl; re tur n 0 ; } W he nco mpiledan dex ecuted,th epr ogramge neratesth efo llowingoutput: *Be for ept rswap():p i: 10 *p j: 20 Af te rpt rswap(): p i: 20 p j: 10