Category : C Source Code
Archive   : CPPTOUR.ZIP
Filename : CPPTOUR.HTX

 
Output of file : CPPTOUR.HTX contained in archive : CPPTOUR.ZIP
Ÿ$Ÿ$¶~$kô–ANSI SYS ~‘#ÿý@ÃHyperHelperþ HyperHelper±.5Ãopyright¨c)±988,1989âyÂryanÆlamig
þALLÒIGHTSÒESERVED

Thisèelpóystem÷asãreated÷ithÈyperHelper,áÓhareWareðroduct
whichéncludesáèypertextârowserándãompiler.Éndividualsáreæree
toãopyándäistributeÈyperHelper,ðrovidedétésäiÿý@stributedÏNLYén
itsïriginal,õnmodifedæorm,ándôhatÎOÆEEésãharged÷ithout
permissionæromôheáuthor.

IfùouôryÈyperHelperándäecideôoõseét,ùouãanòegisterùour
copyâyóending¤20öiaãheck,íoneyïrder,ïrÖisa/Mastercardôo:

þEinÓtein'sÃomputers,·50ÂridgeÓt,ÙubaÃiÛýty,ÃA¹5991
þPhone:¹16-671-7444

Thoseòegistering÷illòeceiveôheìatestöersionïfÈyperHelper,álong
witháðrintedõser'sçuide,áãontextóensitive,íemoryòesident
versionïfôheârowser,ándénformationïnæutureånhancements.ŠøèÑ ýTÿý)ªhomeÿ
þAÈyperGuideôoÃ++
þ
þCopyright¨c)±989âyÂryanÆlamig
þALLÒIGHTSÒESERVED
þ
þYouãanæreelyãopyándäistributeôhisäeckándôheássociated
þhypertextârowser.Èowever,ôhisäeckésæorðrivateõseïnly.
þItãannotâeóoldïräistributedæoráæee,ándãannotâeíod§ýÓified
þinány÷ay÷ithoutðermissionæromôheáuthor.Ôheássociated
þhypertextârowserésðartïfÈyperHelper,áóharewareèypertext
þdevelopmentóystemãreatedâyôheáuthor.
þ
þý
*ÊýîÒhome01ÿ
þHelpïnõsingôheÈyperHelperârowser
þ

þ

þ

þ
AreùouîewôoôheÈyperhelperÂrowser?Éfóo,óelect
þ
'yes'âyðressingôheópaceâar,ándôhenðressòeturn.
þ
Otherwise,êustðressòeturnîowôoóelect§no':
þ ý &(—ý¦home02ÿ
þ Here×eÇo
þ
þ×hatésÃ++?
þ
þÔheÆeaturesïfÃ++
þ
þÒidingôheÏbject-OrientalÅxpress
þ
þÂridgingôheÇap
þ
þÆoríoreénformationHý< '
6
 $ f( $
ÿýµhelp01
þHelpïnÕsingôheÈyperHelperÂrowser
þ
þTheÈyperHelperÂrowseròeadsópeciallyãreated
þhypertextæilesándäisplaysôhemásáóeriesïfãards.Ïn
þtheãardsáre¢hot"ìinksôoïtherãards,õsuallyäisplayed
þinâold.Ôoóelectáìink,íoveôheèighlightedâarôoôhe
þlÿýµinkándðressòeturn.Ôheârowser÷illêumpôoôheãard
þassociated÷ithôheìink.
þ
þNote:Ôoíoveôheèighlightedâar,õseôheárrowëeys,ïr
þtapôheópaceâar.
þ
þForíoreénformation,óelectôheæollowingôopics:
þ
þ Ôheávailableëeyãommands
þ Õsingôheãommandìineâar
þ ý)ÅditingÓtrings
þ Ïr>ý2 '' & ÿý
<keysþTheæollowingëeysãanâeõsedénôheÈyperHelperârowser:
þ
þf,ÆþChangeæiles
þh,È,ÈOMEþDisplayôheèome¨first)ãardénäeck
þp,ÐþGoâackwardsôo÷hereùou'veâeen
þn,ÎþGoæorwardsôo÷hereùou'veâeen
þPGUPþGoôoôheðreviousãard¨inîumberedóequence)
þPGDNÿý þGoôoôheîextãard¨inîumberedóequence)
þs,ÓþSearchæoráëeyword
þq,Ñ,ÅSC,ÁLT-X Ñuitôheârowser
þ
þArrowËeysþMoveároundôheìinksïnôheãard.
þ
þShiftÁrrowËeys Íoveôheèypertextãardïnôheócreen.
þ
þENTERþ
Jumpôoôheãardássociated÷ithôhe
þlinkâeingèigh:ýHlighted.
þ
þInáddition,ôheseándïtherëeysãanâeõsed÷h ýÿýW ácmd01

þUsingôheÍainÃommandÂar
þ
þHyperHelperèasáãommandâarátôheôopïfôheócreenôhat
þincludesãommandsôo:
þ
þ
ýðþDisplayôhe¢AboutÈyperHelper"ãard
þ
File ÃhangeèypertextÆiles
þ
Home Çoôoôheæirstãardénôheäeck
þ
Prev Çoâackwardsôo÷hereùou'veâeen
âýhþ
Next Çoæorwardsôo÷hereùou'veâeen
þ
Srch Óearchæoráëeyword
þ
Quit Ñuitôheðrogram
þ
þToóelectïneïfôheseãommands,ðressôheÅnterëey
þwhileôheèighlightedâarésïverôheäesired÷ord.Ásá
þshortcut,ùouãanálsoôypeôheæirstìetterïf ý% # ÿý[¿switch01ÿ
þChangingÆiles
þ
þ
þIfùouèaveïtherÈyperHelperäecks,ùouãanówitchâetween
þthem÷hileénôheârowserâyõsingôhe¢File"ãommandâar
þoption,ïrâyðressing¢f".Ùou÷illâeðromptedæorá
þnewæileîame,÷hichùouôypeéntoánåditæield.
þTheæileîameãanâeçiv·ýen÷ithïr÷ithoutôheássumed
þ".htx"åxtension.
þ
þ Ifôheæileäoesn'tåxist,ùou÷illòeceiveánårror
þmessage.Ðressòeturn,ándôhenôypeénáîewæileîame.Ùou
þcanábortôheæileãhangingóessioný
-
6

ÿý*²srch01
þKeywordÓearch
þ
þYouãanäoáëeywordóearchôhroughôheäeckïfãardsâyõsing
þtheÓrchãommandâarïption,ïrâyðressing¢s".Ùou÷illâe
þpromptedæoráìistïfëeywords,÷hichùouôypeéntoánåditæield.
þTheëeywordsóhouldâeóeparatedâyópaces.ÈyperHelper÷ill
þfÿý*indándêumpôoôheæirstãardôhatèasáíatchingëeyword,
þscanningæromìeftôoòightôhroughôheëeywordìist.
þ
þBecauseôhe÷ordsáreócannedìeftôoòight,ùouóhouldôype
þinôhe÷ordsénïrderïfémportance,÷ithôheæirst÷ord
þbeingùouræirstãhoice.
þ
þNote:Ôheseëeywordsá©ýŸreîoténôheôextétself,âutòather
þ
wereáttachedôoôheãards÷henôheäeck÷asâuilt.
þ
Theyéndicateôheíainôopicïfôheãard.
þ
þIfîoëeywordésæound,ùouãanôryïthers.ÕseôheÅSCëeý
<E
ÿýëedit01
þTheÅditÆield
þ
þTheåditæieldáppears÷heneveráótringésôoâeénput.
þItésõsuallyèighlighted.Æoråxample:
þ
þýÚÿÄý¿
þý³ÆileÎame: ÿ÷.ÿ÷ ý³
þýÀÿÄýÙ
þ
þ Youãanôypeãharacterséntoôheæield,ándõseôheÁRROW
þkeysôoíoveìeftôoòight.ÙouãanálsoõÿýëseôheÂACKSPACE
þandÄELëeysôoäeleteãharacters.Ùouãanôoggleénsert
þorïverwriteíodeâyõsingôheÉNSëey.Ôheôext÷illócroll
þifôheótringésìongerôhanôheæield.Álso,ÈOMEôakes
þyouôoôheâeginningïfôheótring,ÅNDôakesùouôoôhe
þend.ÙouãanðressÒETURN÷henæinished,ýÆïrðressÅSC
þtoábo ý!, -4
ÿý$Nedit02ÿ
þEditingôheÌastÉnputÓtring
þ
þTheìasténputótringãarriesïveréntoôheîextåditás
þtheäefault.Ðressingïneïfôheåditëeysásôheæirst
þcharacteròetainsôheótringæorãonvenientåditing.
þHowever,ðressingányïtherãharacterásôheæirst
þcharacterãausPýæesôheótringôoâeóetôoîull,óoôhatùouãan
þconvenientlyôypeénáîewótring.
þ,Comý
,:&-ÿýŒmore_infoþForÍoreÉnformation
Š ÂooksáreêustâeginningôoáppearïnÃ++.Èereáreóomeïfôhe
ãurrentôitles:
Šþ¢TheÃ++ÐrogrammingÌanguage"¨Addison-Wesley),ÂjarneÓtroustrup
Šþ¢TheÃompleteÃ++Ðrimer"¨AcademicÐress/HBJ),
þBryanÆlamig,Ëeith×eiskamp
ŠþÿýŒ¢TheÃ++ÐrogrammingÌanguage"¨Sams),ÊohnÂerry
Šþ¢AnÉntroductionôoÏbject-OrientedÐrogrammingándÃ++"
þ(Addison-Wesley),ÒichardÓ.×einer,ÌewisÊ.Ðinson
Šþ¢C/C++ÆorÅxpertÓystems"¨MISÐress),ÄavidÈu
Šþ¢C++æorÃÐrogrammers"¨BenjaminÃummings),ÉraÐohl
&ýüŠþ¢UsingÃ++"¨McGrawÈill),ÂruceÅý
4 &-ÿýÊNadvertiseþTheÃompleteÃ++Ðrimer
Š Átìast®..áãompleteðrimerôoèelpùouíasterôheðowerfulîew
åxtensionôoôheÃìanguage­-Ã++.
Š ÔheÃompleteÃ++Ðrimerésîoókimpyòeferenceíanual.Åveryæeature
ïfÃ++ésçivenáôhoroughôreatment.Ùetátôheóameôime,ôhis
ðrimerésôhÿýÊeæirstçuidebookándôutorialôoðresentÃ++ðrogramming
énáæriendly,åasy-to-followæormat.×rittenénáèands-onótyle,÷ith
îumerousóhortâutõsefulåxamples,ôhisâookôakesùouôhrougháll
áspectsïfÃ++ðrogramming.Èereáreóomeïfôheôopics:
ŠþÁóolidéntroductionôoïbjeÿýÊct-orientedðrogramming
þÁôhoroughäiscussionïfãlassesándïbjects
þÁãompleteìookátôheîewôypesïfæunctionsávailableénÃ++
þÁãompleteäiscussionïfïperatorïverloading
þÔechniquesæor÷orking÷ithénheritance
þÁãompleteåxplanationïfôheÃ++ótreamÉ/Oóystem
Xý þÓpecialïbject-orientedðrogrammingðrojects
Š Íakeôhisäefinitiveôutorialùourðerso ý2ÿý08about_author
þAboutôheÁuthor
þ
þBryanÆlamigésánåxperiencedóoftwareäeveloperòesiding
þinÓcottsdale,Árizona.ÈeésánåxperténäevelopingÃ,
þC++,ándÐrologápplications.Èeésão-authorïfôheâook
þ"AdvancedÔurboÃÐrogrammer'sÇuide,"¨John×iley¦Óons),
þandÿý0ôheæorthcomingâook¢TheÃompleteÃ++Ðrimer"¨Academic
þPress).
þ
þBetweenèisópareôime,¨whatópareôime),Âryanìikesôoðlay
þbluegrassæiddleándåxploreôheäesertóurroundingÓcottsdale.
þ
þYouãanòeachÂryanây÷ritingôo:
þ
þBryanÆlamig
þ16801Î.´9thÓt.,Ápt²0+ý&3
þScottsdale,ÁZ¸5254
þ
þOr,ùouãanò ý2ÿýiwhatisc++þIntroducingÃ++
þ
þQ:×hatésÃ++?
þA:Ét's¢C÷ithÃlasses."
þ
þC++ésánåxtensionôoôheðopularÃðrogrammingìanguage.
þIt÷asäevelopedâyÂjarneÓtroustrupátÁT&T,ándïwes
þmanyïfétsæeaturesôoôheæirst¢object-oriented"
þlanguage­Óimula67.
þ
þThÿýieíainæeatureïfÃ++ésôheãlassãonstruct÷hich
þallowsùouôo÷rapõpæunctionsándäataéntoéndividual
þpackages.Ôheseðackagesáreãalledïbjects,ánd
þprogramming÷ithïbjectsésãalledïbject-oriented
þprogramming¨OOP).
þ
þWhyîotôakeôheðlungeándóee÷hatÃ++ìookìikeýQs
þrightý
/&-ÿý ªfast01þTakeôheÐlungeéntoÃ++
Šþ5TheÃliffsïfÃ
Èere'sùouræirstÃ++ðrogram:þp ­ÿ-
þ/o ¯
þ#include¼stdio.h>þ|
þvoidíain()þo ü
þ{þ-/
þinté,ê;þÿ ÷
þ(C++×aters
þi½²5; ê½±7;
Šþprintf("Theõltimateánswerés¥d\n",é+j);
þ}
Š Óurprise!Étäo¥ý{esn'tìookányäifferentôhanáÃðrogram,îowäoes
ét? Ôhat'sâecauseíostÃðrograms÷illãompileöirtuallyõntouched
énÃ++.Èowever,Ã++èasîumerousåxtensions.
ŠþFirstìooý
1&-ÿýL"-fast02þFirstÌooksátÃ++Åxtensions
Š¯/ÙouræirstìookátópecialÃ++æeatures ‘ÿÄÁîewótyleïfãomments
Š £include¼stream.h>þ//ÁîewótreamÉ/Oìibrary
Š ãlassãomputerûþ //Áîew÷ayôoâuildótructures
þintíemory_bank;þ //÷ithäataÁNDæunctions.
ðublic:
þvoidádÿýL#d(intá,éntâ)û¯/Áæunctionôhat'sálso¢inline"
þmemory_bank½á«â; ¯/Ótoringäataénánïbject
þcout¼<¢Theõltimateánswerés:¢¼<íemory_bank;
þ};þ
};þ ýÀÿÄ Áîew÷ayïfäoingÉ/O
Š öoidíain()
û
þcomputeräeep_thought;þ//Íakingánïbject
þdeep_thought.add(25,±>ý˜7); ¯/Ándôalkingôoét
}
þTellíeíoreáboutÃ++'sæeatures®.ý
5&-¦ý¥¥feat01ÿ
þ
þC++ÐacksáÌotïfÐowerfulÆeatures
þ
þýÚÿÄý¿
þýÚýÄýÙÃ++ ý³ ÏOPÓupport ÏtherÎiceties
þÿ =ß½ÿ
=ß½ÿ
=
þO ÏþOþOþOþO
þ ÿ2-
þ
þBackôoÍainÍe*ý ' + 8 .ÿýt%feat02

þOOPÓupport
þ
þ
þTheðurposeïfíanyïfÃ++'sæeaturesésôoóupportïneôhing:
þ
þObject-OrientedÐrogramming¨OOP)
þ
þ
ÃlassesþÃonstructors
þ
ÏbjectsþÄestructors
þ
ÍethodsþÖirtualÍethods
þ
Énheritanceþ
Æriends
þ
þInæact,÷e'veárran‰ý¶gedáçuidedôourôhroughÏOPãountryïnôhe
þ"Object-OrientalÅxpress."Éfùou'reánéndividualist,ùouãan
þsimplyåxploreôheôopicsïnùourïwn.
þpýd  5# . #

#
-
(  -# 1   ># ) ‰*^6Î5¾ÿýo']feat03


þOtherÎiceÆeatures
þ
þ
þ C++èasïtherîiceæeatures¨besidesÏOP)ôhatóimply
þ makeétá¢betterÃ":
þ
þ ÆunctionÐrototypingþÄefaultÁrguments
þ ÉnlineÆunctionsþ ÒeferenceÖariables
þ ÆunctionÏverloadingþÎew¦Äelete
þ ÏperatorÆunctionsþ
TýÒÓtreamÉ/OÃlasses
þ
þ Feelæreeôoåxploreôheseæeaturesátùourìeisure.
þ
þBackôoÃfýZ
{+ ; z


€+
=
w
^+ 6 |
 `+ < ~4%ÿý+)Sobj01þRidingôheÏbject-OrientalÅxpress
þ
þoïð ïïð ïïð
þo
þo
þo
þ
o
þ ýÜ
þ
ýÚýÄýßÿÄý¿ ýÚÿÄý¿ ýÚÿÄý¿ ýÚÿ Äý¿ ýÚÿÄý¿
þýÚýÄýÙObjectsý³ ý³Classesý³ ý³Methodsý³ ý³Inheritanceý³ ý³ Ånd ý³
þý³ÿ _ý³__ý³ÿ_ý³__ý³ÿ_ý³__ý³ÿ _ý³__ý³ÿ_ý³
þÿý+*
oo ïoþooïoþooïoþoo ïoþooïo
þÿ=+ÿ=+ÿ=+ÿ=+ÿ=+ÿ=+ÿ=+ÿ=+ÿ=+ÿ=+ÿ=+ÿ=+ÿ=
þ
þTheÏbject-OrientalÅxpressésáboutôoåmbarkïnáôour
þthroughÏOPãountry. Äon'tíissïutïnôheôrip!
þ
þSelectôheâoxcarïfùourãhoice,ándèopïn!Óhouldùouçet
þside-trac[ýókedäownóomeæorgottenðath,êustóelectôhe¢OOE"
þlinkóhownïnåachãard,÷hich÷illôransportùo>ý2    5! ' -, 6 >= ?  +ÿýÆ+çobj01a

þThoseÍysteriousÏbjects
þ
þ
þEverybody'sôalkingáboutôhemôheseäays,âutæewèaveáctually
þpaidôhemáöisit.Óo÷e'veárrangedáôripóoôhatùouãanåxplore
þtheãountrysideándôalkôoôheìocalæolksïfÏOPãountry.Ôhe
þorderïfôheöisitsésõpôoùou,âutèere'sáÞý óuggestion:
þ
þ×határeïbjects,ányway?þTheÌocalÆolks
þÓtoringÄataénÏbjects
þÍakingÏbjectsÄoÓomethingþo
þÔalkingôoÏbjectsþ/o\
þÉnitializingándÄestroyingÏbjectsþ p
þÅxtendingÏbjects
þ
þOOE‘ÿÄÒememberôhRýF

   " -

3*"> 1ÿýø-·obj02a

þWhatáreïbjects?
þ
þObjectsáreõnitsïfãode¨thatés,æunctions)ándäata¨simple
þvariablesándótructures)állòolledéntoéndependentðackages.
þTheseðackagesáreôheâuildingâlocksïfùourðrogram.
þ
þHereáreóomeóampleïbjects:
þ
þ Window:þPiggyÂan·ý*k:
þ
þ ýÚÿÄý¿þýÚÿÄý¿
þ ý³éntø,ù,÷d,èt; ý³þý³äoubleóavings;þý³
þ ý³öoidäraw();þý³þý³öoidäeposit();þý³
þ ý³öoidèide();þý³þý³äouble÷ithdraw(); ý³
þ ýÀÿÄýÙþýÀÿÄýÙ
þ
þ ý02
ÿýÑ/^obj02þMoreáboutïbjects
þ
þ
þObjectsáreìikeìittleíiniatureðrograms.Ôheyãanèoldâoth
þdataándæunctions¨whicháreãalledíethods).Ôypically,ôhe
þdataésèidden,ándíustâeáccessedây¢passingíessages"ôo
þtheíethodsïfôheïbjects.
þ
þýÚÿÄý¿
þý³ÔellerÍaÿýÑ0chineþý³
þý³Ïbjectþý³
þý³þýÚÿÄý¿þý³
þý³þ ýÚ<ýÄý´DepositýÃÿÄý³ýÄ<<¢Deposit¤100"
þý³ ýÚÿÄý¿ ý³ ýÀÿÄýÙþý³
þý³ ý³$$$ýÃ<ýÄ>ý´ Íethodsþý³þMessageÐassing
þý³ ýÀÿÄýÙ ý³ ýÚÿÄý¿þý³
þý³ ÄataþýÀ>ýÄý´WithdrawýÃ<ýÄ>ýÂÿÄý³ýÄ<< ¢NýBWithdraw¤500"
þý³þýÀÿÄýÙ ýÀÿÄý³ýÄ>> ¤$$ÐartyÍoney!
þý³þý³
þý³þý ý+=@B
ÿýA2Oobj03
þTheÉngredients
þ
þWhatáreìittleïbjectsíadeïf?Îo,îotóugarándópice.Áctually,
þthey'reâuiltærom÷határeãalledãlasses.Ôheseãlassesáre
þsimilarôoÃótructures,åxceptôheyãanèaveæunctioníembersás
þwellásäataíembers.ÔheæunctioníembersáreãalledíeÿýA3thods.
þ
þclassôeller_machineûþ//Ãlassäeclaration
þpublic:þ//Äataèidingãontrol
þ
doubleâig_bucks;þ
//Äataíember
þ
voidäeposit(doubleámt); ¯/Íethod
þ
double÷ithdraw(void);þ//Ánotheríethod
þ};
þ
þClassesóerveásáôypingíechanismæorïbjects,ðrovidSýping
þa÷ayôoãlassifyïbjectséntoçroups÷ithóimilarôraits.
þ
þObjectsásÏOPÂuildHý<(,5( 2 9(
+
( - -$*,ÿýÞ4õobj04þObjectsáreÏOPÂuildingÂlocks
þ
þObjectsáreôheâuildingâlocksïfïbject-orientedðrograms
þtheóame÷ayôhatótructuresáreôheâuildingâlocksïf
þtraditionalìanguagesìikeÃándÐascal. Ôheäifferenceés
þthat÷ithïbjectsùouãaníoreåasilyéncorporateæunctio÷ýŠnsénto
þtheseâlocks.
þ
þ!ýÉÿ Íý»
þ BuildingÂlocksþýºÔeller ýº
þ ForÁÂankingþ ýºÍachine ýº
þ Systemþýºþ ýº
þ!ýÈÿ Íý¼
þýÉÿ Íý»ýÉÿ Íý»
þýº Ìoan ÿºÁccting ýº
þýºÏfficer ÿºÆirmþýº
þýºþ ÿºþ ýº
þýÈÿ Íý¼ýÈÿ Íý¼
þ
þ
PackagingÕpÆunctio ý
#/1$ 'ÿý÷6Aobj05þPackagesïfÃode
þ
þCèasäataótructuresándöariables,ándétèasæunctions.
þHowever,Ãäoesn'tðutôheseãomponentsôogetheröery÷ell.
þC++,¨andïtherÏOPìanguagesìikeét),äoðutôhemôogether
þwell.Ãlassesóerveôoäefine÷hatâelongsôogether,ánd
þobjectsáreÿý÷7éndividualòealizationsïfôheseãlasses.
þ
þDataþ
Combined
þ UsingÃlasses
þ ýÚÿÄý¿
þ ý³äoubleâig_bucks; ýÃÿÄý¿
þ ýÀÿÄýÙþý³þýÚÿÄý¿
þ%ý³þý³þý³
þFunctionsþ
ýÃÿÄ ý³Ôelleríachine ý³
þ%ý³þý³þobjectsþý³
þ ýÚÿÄý¿þý³þý³þý³
þ ý³öoidäeposit();Iý þýÃÿÄýÙþýÀÿÄýÙ
þ ý³äouble÷ithdraw(); ý³
þ ýÀÿÄýÙþCreatingÏbjec ý%48:$ 'ÿýb9jobj06


þ
þClasses:¢CookieÃutter"ÏbjectÍakers
þ
þ ýÚÿÄý¿
þ ý³Objectý³
þRawÂytes ý³Maker ý³ Ïbjects
þ ýÔÿÍÿ³ÿÍý¾
þÿÛ ÿÁ ÿÜ ÿÜ ÿÜ ÿÜ
þÿ,Í
þ
þJustásÃótructuresáreõsedásôemplatesæoríakingöariables,
þclassesóerveásïbject¢cookiký¶eãutters." Æromåachãlassãome
þobjectsïfôheóameíakeándíodelòightïffôheássemblyìine.
þ
þMakingÔellerÏ ý(24$ 'éýÍðobj07ÿ
þMakingÔellerÍachineÏbjects
þ
þ
þ Theôellerãlassóervesásáôemplate,ærom÷hich
þ tellerïbjectsáreãreated:
þ
þ
þýÚÿÄãlassþýÚÿ ÄýÂÿÄôellerïbjects
þþ þ 
þteller_machineâroke_bank,ãold_cash_inc;
þ
þ
þObjectÔ*ý(-/$
)ÿý<dat01þStoringÄata÷ithÏbjects
þ
þObjectsáreòeallyêustöariablesãreatedæromótructures.Ìike
þanyótructure,ùouãanótoreäataénïbjects.
þ
þýÚÿÄý¿þ classôeller_machineû
þý³ÔellerÍachineþý³þ public:
þý³Ïbjectþý³þ doubleâig_bucks;
þý³þýÚÿÄý¿þýÿýæ³þ ...þ|
þý³þ ýÚ<ýÄý´Depositý³ÿÄý³ýÄ<<þ};þ|
þý³ ýÚÿÄý¿ ý³ ýÀÿÄýÙþý³þ|
þý³ ý³$$$ý³‘ÿ&-ýÙ
þý³ ýÀÿÄýÙ ý³ ýÚÿÄý¿þý³
þý³þ ý³ ý³þý³ÿÄý³ýÄ<<
þý³ ÄataþýÀ>ýÄý´Withdrawý³ÿÄý³ýÄ>>
þý³þýÀÿÄýÙþý³
þý³þý³
þý³þMethodsþý³þ ý,=,." $ÿý%>Fdat02þAccessingÄata
þ
þYouáccessôheäataïfánïbjectêustìikeùou÷ouldáíember
þofáÃótructure,÷ithôhe§.'îotation.Æorénstance:
þ
þclassôeller_machineû
þpublic:
þdoubleâig_bucks;
þ...
þ};
þ
þteller_machineíy_bank;
þ
þ
þObject ÿÄý¿þýÚÿÄÄaHýta
þþ
þmy_bank.bigbucks½±ÿ0.00;
þ"
þDot ÿÄýÙ
þ
þHidingÄa ý')" $ÿý?
dat03
þHidingÄata
þ
þOfãourse,ùouäon't÷antåverybodyôoâeábleôoáccess
þyourâigâankáccount.Äon't÷orry,ùouãaníakeôheäata
þofánïbjectðrivate. Èere'sánåxample:
þ
þ
classôeller_machineû
þ
private:þ//ðrivateëeyword
þ
doubleâig_bucks;þ
//ðrivateíembÿý@er
þ
public:þ//ðublicëeyword
þ
voidäeposit(doubleámt); ¯/ðublicíember
þ
double÷ithdraw(void);þ//ðublicíember
þ
};
þ
þNote:Ôheðrivateëeywordésïptional. Ányíemberâefore
þtheðublicíemberésáutomaticallyðrivate,õnlessïtherwise
þspecified.
þ
þ
Accesý(singðriva4ý(+1;+
0
:
" -/ ÿýÓAEdat04


þPrivateÍembers
þ
þ
þPrivateíembersãan'tâeáccessedïnôheïutside.Æor
þinstance,çivenôheãlassæromôheðreviousãard,
þtheæollowingéséllegal:
þ-Can'täoéfâigbucks
þ teller_machineóhaky_savings;þisðrivate!
þ1ý³
þ shaky_savings.bigbucks½±ÿ0.BýB00;‘ÿÄýÙ
þ
þThenèowªare*ðrivateíembersáccessed?Óelectíe,Éë*ý+71A!"$&(ÿýACîdat05þPrivateíembers¨cont)
þ
þPrivateíembersïfáãlassãanâeáccessedâyôheíethodsïf
þtheãlass:
þ
þscopingïperator ÿÄý¿
þassociatedãlass ÿÄý¿þý³ ýÚÿ Äíethod
þ ý³þý³ ý³
þ þ Ÿ
þvoidôeller_machine::deposit(doubleámt)
þ{
þbigbucks«=ámìý]t;
þ} ž
þýÀÿÄïkayôoáccessðrivateíemberèere
þcauseôhisíethodâelongsôoôeller
þmachineãlass
þ
þYouäon'tèaveôhisðroblem÷ithðublicíembers.Ányone
þcançetôoôhem,åvenéfôhey'reîotíethodsïfôheãlass.
þ
þ Foríoreäetailsïnäataèiding 4ý(9?- )9-6:< ÇýwÔctordtor01


þConstructorsándÄestructors
þ
þ
þ
þ
þC++ðrovidesãonvenient÷aysôoénitializeándãleanupáfter
þobjects,ôhroughôwoópecialëindïfíethods:
þ
þ Ãonstructors
þ Äestructors
þ
þ
4ý(
 #
 ($)+ ÿý`Fwctor01


þInitializingÄata×ithÃonstructors
þ
þObjectsãanèaveópecialíethodsãalledãonstructors÷hich
þareõsedôoénitializeôheïbject.Ôheseíethodsèappenôoèave
þtheóameîameásôheîameïfôheãlass:
þ
þ classôeller_machineû
þ doubleâig_bucks;
þ public:
þ{ý– teller_machine(doubleámt);‘ÿÄãonstructor
þ voidäeposit(doubleámt);
þ double÷ithdraw(void);
þ };
þ
þMakingãonstruct ý)$.0
ÿýýGGctor02


þMakingãonstructors
þ
þGivenïurãlassæromôheðreviousãard÷eãanäefine
þourãonstructorás:
þ
þ scopingïperator ÿ Äý¿
þ associatedãlass ÿÄý¿þý³þýÚÿÄãonstructor
þý³þý³þý³þname
þþþ
þteller_machineº:ôeller_machine(doubleámt)
þHýª{
þbigbucks½ámt; ‘ÿÄénitializeäata
þ}
þ
þDeclaringãonstructors*ý!-#.%35"
$ÿýqI%ctor02a


þDeclaringãonstructorsénline
þ
þ Youãanálsoäeclareãonstructorsénline:
þ
þclassôeller_machineû
þdoubleâig_bucks;
þpublic:
þ//énlineãonstructor
þteller_machine(doubleámt)ûâig_bucks½ámt; }
þvoidäeposit(doubleámt);
þdouble÷ithdraw(-ýÁvoid);
þ};
þ
þCallingÃonstructors®..þ*ý-2€,&13"
$ÿýÊJ¸ctor03
þCallingÃonstructors
þ
þYouäon'tòeallyãallãonstructorsôhe÷ayùouäoîormal
þfunctions.Ùouóetõpôheæunctionãallátôheóameôime
þyouäeclareôheïbject.Âyçivingùourïbjectsðarameters,
þyou'reôellingétôoðassôheseárgumentsïnôoôhe
þconstructor:
þ
µýÑþ class ÿÄý¿þýÚÿÄïbject
þ nameþý³þý³
þþ
þ teller_machineãounterfeit_bank_of_AZ(1ÿ0.00);
þ#þ
þ#ýÀÿÄýÂÿÄýÙ
þ,ý³
þCausesãonstructorôoâeãalled
þ
þWhenáreãonstruc ý.'24&
(ÿý¡Lsctor03b

þWhenáreãonstructorsãalled
þ
þTheãonstructoræoránïbjectésãalled÷heneverôhatïbject
þcomeséntoócope.Æorénstance,ánïbjectìocalôoáæunction
þcomeséntoócope÷heneverôheæunctionésãalled.Èereés
þanåxample:
þ
þ voidäoit(void)
þ {
þ teller_matýìchineôelly(1000.0);‘ÿÄãonstructorãalledèere
þ ...
þ }
þ
þ Whenõsingäynamicíemory®..
þ Destructors®..
þ
þ Tou4ý( %, (  ÿýKN‘dtor01

þ Destructors
þ
þDestructorsáreôheãounterpartôoãonstructors.Ôheyáreõsed
þto¢cleanup"áfteránïbject.Áäestructorèasôheóameîameásôhe
þclass,÷ithá§~'¨twiddle)ðuténæront:
þ
þclassôeller_machineû
þ
doubleâig_bucks;
þpublic:
þ
teller_machin–ýe(doubleámt);‘ÿÄãonstructor
þ ~teller_machine(void);þÿÄäestructor
þ
voidäeposit(doubleámt);
þ
double÷ithdraw(void);
þ};
þ
þMakingÄestructo ý)).0 ÿýPBdtor02


þMakingäestructors
þ
þGivenïurãlassæromôheðreviousãard÷eãanäefine
þouräestructorás:
þ
þ scopingïperator ÿ Äý¿
þ associatedãlass ÿÄý¿þý³þýÚÿÄäestructor
þý³þý³þý³þname
þþþ
þteller_machineº: ~teller_machine(doubleámt)
þ{Cý
þprintf("Machingçoingäown\n");
þ}
þ
þDeclaringäestructors*ý!-(.*35ÿýrQpdtor03

þDeclaringäestructorsénline
þ
þYouãanálsoäeclareäestructorsénline:
þ
þclassôeller_machineû
þ
doubleâig_bucks;
þpublic:
þ
//énlineãonstructor
þ
teller_machine(doubleámt)ûâig_bucks½ámt; }
þ
//énlineäestructor
þ
~teller_machine(void)ûðryý-intf("Machineçoingäown®..\n"); }
þ
voidäeposit(doubleámt);
þ
double÷ithdraw(void);
þ};
þ
þCallingÄestructors®..þ*ý%*€++02ÿýSldtor04ÿ
þWhenáreäestructorsãalled
þ
þTheäestructoræoránïbjectésãalled÷heneverôhatïbject
þleavesócope.Æorénstance,ánïbjectìocalôoáæunction
þleavesócope÷henôhatæunctionòeturns.Æoråxample:
þ
þ voidäoit(void)
þ {
þ teller_machineôelly(1000.0);‘pý<ÿÄãonstructorãalledèere
þ ...
þ }‘ÿÄäestructorãalled÷henåxecutionòeachesèere
þ
þWhenäynamicíemoryésõsed ý-,68,.ÿý©T+dtor05þConstructorsándÄestructorsándÄynamicÍemory
þ
þConstructorsándäestructorsáreïftenõsedénãonjunction÷ith
þdynamicíemory.Ùouíightõseáãonstructorôoállocate
þmemory,ándáäestructorôoäe-allocateét:
þ9TourÇuide
þclassótringûþ#OOE
þ
charªdata;¯ÿý©U/ðointôoótringäataþ FeatureÍenu
þ
intóize; ¯/óizeïfôheótring
þpublic:
þ
//állocateíemory
þ
string(intóz)ûäata½îewãhar[size½óz]; }
þ
//äe-allocateíemory
þ ~string(void) ûäeleteäata; }
þ};
þ
þvoidäoit(void)
þ{
þ
stringó(25);‘ÿÄãonstructorálloca;ýPtes²5âytes
þ}‘ÿÄäestructoräe-allocatesïnæunctionòetu4ý( |9B9;9D ÿýWòmet01þ"Methods
þ
þ Objectsãanèaveíethods.Ôheseáreæunctionsôhatèandle
þ theåverydayãhoresïfôheïbjects.Æorénstance,ïur
þ telleríachineèasíethodsôoäepositánd÷ithdrawíoney.
þ
þ ýÚÿÄý¿
þ ý³ÔellerÍachineþý³
þ ý³Ïbjectþý³
þ ý³þýÚÿÄý¿þý³
þ ý³þ ýÚ<Þý^ýÄý´Depositý³ÿÄý³ýÄ<<
þ ý³ ýÚÿÄý¿ ý³ ýÀÿÄýÙþý³
þ ý³ ý³$$$ýÃ<ýÄ>ý´þý³
þ ý³ ýÀÿÄýÙ ý³ ýÚÿÄý¿þý³
þ ý³þ ý³ ý³þý³ÿÄý³ýÄ<
þ ý³ ÄataþýÀ>ýÄý´Withdrawý³ÿÄý³ýÄ>>
þ ý³þýÀÿÄýÙþý³
þ ý³þý³
þ ý³þMethod4ý(

. /1:>@ ÿý.Ysmet02a


þAñuickìookátôheäeposit()íethod
þ
þWhatäoíethodsìookìike?Èere's÷hatôheäeposit()íethod
þforïurôelleríachineïbjectsíightìookìike:
þ
þscopingïperator ÿÄý¿
þassociatedãlass ÿÄý¿þý³ ýÚÿ Äæunctionîame
þreturnôype ÿÄý¿þ ý³þý³ ý³rýŠþýÚÿÄárgument
þþ þ Ÿþ
þvoidôeller_machine::deposit(doubleámt)
þ{
þbigbucks«=ámt;
þ}
þ
þHow'sô ý(1-/(1ÿýÂZómet02bþAñuickìookátôhe÷ithdraw()íethod
þ
þWhatäoíethodsìookìike?Èere's÷hatôhe÷ithdraw()íethod
þforïurôelleríachineïbjectsíightìookìike:
þ
þscopingïperator ÿÄý¿
þassociatedãlass ÿÄý¿þý³ ýÚÿ Äæunctionîame
þreturnôype ÿÄý¿þ ý³þý³ ý³þõý£ýÚÿÄárgument
þþ þ Ÿþ
þdoubleôeller_machine::withdraw(doubleámt)
þ{
þbigbucks­=ámt;
þif¨bigbucks¼°.0)û
þprintf("Sorry,Ãharlie,ùou'reïverdrawn!\n");
þbigbucks­=±0.0;¯/ãhargeæorïverdraft
þ}
þreturnâigbucks;
þ}
þ
þHow'sôhis ý(0-/(1ÿýÙ\met03bþScopingïfíethods
þ
þMethodsáren'tñuiteìikeïrdinaryæunctions.Ôheyìookðretty
þmuchôheóame,âutôheyèaveópecialáccessôoôheïther
þmembersïfánïbject.Ópecifically,ôheyãanáccessôhem÷ithout
þusingôhe§.'îotationùouõsuallyõse÷ithïbjectíembers:
þÿý¹
þdoubleôeller_machine::withdraw(doubleámt)
þ{
þnoteáccess ÿÄý¿
þtoäataïfþ
þobjectþbigbucks­=ámt;
þif¨bigbucks¼°.0)û
þprintf("Sorry,Ãharlie,ùou'reïverdrawn!\n");
þbigbucks­=±0.0;¯/ãhargeæorïverdraft
þ}
þreturnâigbucks;
þ}
þ
þCallingí ý)2.0(1ÿýú^…met03a


þScopingïfíethods
þ
þMethodsáren'tñuiteìikeïrdinaryæunctions.Ôheyìookðretty
þmuchôheóame,âutôheyèaveópecialáccessôoôheïther
þmembersïfánïbject.Ópecifically,ôheyãanáccessôhem÷ithout
þusingôhe§.'îotationùouõsuallyõse÷ithïbjectíembers:€ýÓ
þ
þdoubleôeller_machine::deposit(doubleámt)
þ{
þnoteáccess ÿÄý¿
þtoäataïfþ 
þobjectþ
bigbucks«=ámt;
þ}
þ
þCalli ý)2.0(1ÿýœ`²met04þCallingíethods
þ
þBecauseôheyâelongôoïbjects,ùouãan'tãallíethodsäirectly.
þInstead,ùouãallôhemâyóendingáíessageôoôheïbject:
þ
þObject ÿÄý¿þýÚÿÄÍethod
þþ
þmy_bank.deposit(paycheck);
þþþ
þ familiaräot ÿÄýÙþýÀÿÄýÙ
þ notat¸ýðionæorþ
ýÀÿÄÍessage
þ accessingótructure
þ members
þ
þcash½íy_bank.withdraw(100.00);
þþþ
þý³þýÀÿÄýÙ
þýÀÿÄÒeturnöalueþýÀÿÄÍessage
þ
þTalkingôoÏbjects®..þTourÇuid4ý()/3#3(168 ÿýŠb·msg01þ
Here'sôalkingôoùa­-ôhatés,ÍessageÐassing
þ
þOOPðeopleèaveáäifferentîameæorãallingæunctions.Ét's
þnow¢messageðassing." ×hat'sôheäifference? ×ell,ôheôerm
þmessageðassingãonnotesáíoreåventäriven,íodularîetwork.
þObjectsïperateénðarallel,áÿýŠcndôheyãommunicateâackánd
þforth.
þýÚÿÄý¿þ ýÚÿ Äý¿
þý³ÓhakyÓavings ý³¼ÿÄ> ý³ÂrokeÂank ý³
þýÀÿÄýÙþý³þýÀÿ ÄýÙ
þ%ý³
þýÚÿÄý¿þý³þýÚÿÄý¿
þý³ÃoldÃashÉnc ý³¼ÿÄ> ý³ÃounterfeitÂank ý³
þýÀÿÄýÙþ ý³þofÁZþý³
þ*ýÀÿÄýÙ
þ
þWell,áctually,énÃ++,ïb¹ýjectsäon'tïperateénðarallel.
þWe'reótill÷ithóequentialíachines,äarnétányway!Åven
þso,ôheôermíessageðassingéndicatesôheópiritïfïbjects
þaséndependentìittleâlackâoxes.
þGettingôh ý+402#,ÿýee7msg02þGettingôheÍessageénÃ++
Š ×hatésíessageðassingòeallyìikeénÃ++?×ell,ét'sêustæunction
ãalling.Âutîotêustôoányæunctions,òather,æunctionsôhat
âelongôoïbjects.Ôheseáreãalledíethods.Ôheíethodsáreôhe
íessageóelectors,ôheárgumentsáreôheíessÿýefageãontents.
ŠþTypeïfïbject ÿÄý¿þ
ýÚÿÄÏbject
þþ

þteller_machineíy_bank;
Šþdoubleðaycheck½±00.0; ‘ÿÄðlainïle'Ãöars
þdoubleðarty_money;
ŠþObject ÿÄý¿þýÚÿÄÍethod¨messageóelector)
þþ
þmy_bank.deposit(paycheck);þýÚÿÄíessageãont;ýents
þ0
þparty_money½íy_bank.withdraw(500.00);
þ
þ ý%)+#,ÿýÂgGclass01


þIntroducingÃlasses
þ
þ
þ Classesáreátôheèeartïfïbject-orientedðrogramming
þ inÃ++.Âut÷aitáíinute,÷hyáren'tïbjectsôheãentral
þ feature?Ôheôruthés,÷ithoutãlasses,ùou÷ouldn'tèave
þ objects,âecauseãlassesáre÷hatïbjectsáreâuiltærom.
þ
þ
Dý8×határeãlasses?
þ
Ãlassesásïbjectôemplates
þ
Ãomponentsïfáãl4ý(  6 ) 
#
8#% ÿý þWhatáreãlasses?
þ
þ ClassesáreåxtensionsôoÃótructures.Ôheyádd:
þ
þÄataèiding
þÍethods
þÉnheritance
þ
þ Hereésáóampleãlass:
þ
þclassãircleûþ <ÿÄãlassäeclaration
þdoubleòadius;þ<ÿÄðrivateíember
þpublic:þ<ÿÄðublicíembersæopýSllow
þvoidénit(doubleò);¼ÿÄáíethod
þdoubleárea(void); ¼ÿÄánotheríethod
þ};
þ
þRelationshipôoÓtructu>ý29->,724&(ÿýìjÁclass02bþClassesösÓtructures
Š ÉnÃ++,ùouèaveôheïldÃótructures,îewÃótructures,ánd
ãlasses.Ôheòelationshipâetweenôheôhreeésçivenâelow:
Š Ãótructureþ C++ótructureþC++ãlass
Š ôypedefótructûþstructòectûþclassòectû
þint÷d,èt;þ int÷d,èt;þÿýìkpublic:
}òect;þ
};þint÷d,èt;
þ*};
Š Îoteôhat,õnlikeÃótructures,Ã++ótructuresáreâona-fide
õser-definedôypes,óoùouäon'tîeedôoõseôypedef.Álso,îote
èowáãlass÷ithállðublicíembersándîoæunctionsésêust
ìikeôheÃótructureïfïld.Ã++ótructuresándãlaµýgssesçoâeyond
Ãótructuresénôhatôheyãanèaveæunctionsôoo.
Š Äon'tæorgetôhatùouãanótillèaveÃótructuresénùourãode,ôhat
és,ùouãanõseôypedeféfùou÷ant.Ã++ésõpwardãompatible÷ithà ý+824ÿýÃm.class03þComponentsïfáãlass
þ
þInçeneral,ãlassesãanèaveðublic,ðrivate,ándðrotected
þmembers.Ôheseíembersãanâeïtherïbjectsæromïtherãlasses,
þandíethods¨i.e.æunctions):
þ
þýÚÿ
ÄÃlassëeyword
þý³þýÚÿÄÃlassîame
þþ
þclassóhapeû
þprivate:þÿýÃn
//Ðrivateëeyword
þdataíember ÿÄ énténit_flag; ¯/Ðrivateíember
þprotected:þ//Ðrotectedëeyword
þdataíember ÿÄ äoubleøo,ùo; ¯/Ðrotectedíembers
þpublic:þ //Ðublicëeyword
þ method ÿÄ- énit(doubleø,äoubleù); ¯/ðublicíember
þ method ÿÄ- äo6ý‘ubleárea(void);þ //ðublicíember
þ};
þ
þClassíeRýF.
4
;
. 6 <.3: -$5,. 1ÿýMpŠencap01

þDataÈiding ¨orÄataÅncapsulationásôheôechiesãallét)
Š Š Ôheæancyôermäataåncapsulationêustíeansôoåncloseándèide
äata÷ithináãlass.Ôoèideäataénáãlassíeansôhatïnlyíembers
ïfôhatãlassãanáccessét.
Š Ã++ðrovidesôhreeìevelsïfäataèidin‚ý§g:
ŠþÐublic
þÐrivate
þÐrotected
Š Énáddition,ùouãanèaveæriendæunctionsôoáccess
ðrivateíembersïfãlasses.
ŠþExaRýF  :  ;

<,‰(502 1ÎýÇÑencap02ÿ
þPublicÍembers
þ
þ Publicíembersïfáãlassïbjectáreáccessibleôo
þ anyïtheríemberïfôheãlass,ándôoányæunction
þ oråxpressionénôheðrogram÷hereôheïbjectés
þ inócope.
þ
þPrivateÍembersþClass*ý

;%
.
54
6

)ªýܬencap03ÿ
þPrivateÍembers
þ
þPrivateíembersáreáccessibleïnlyôoïther
þmembersïfôheóameãlass,ïrôoópecial
þfunctionsãalledæriends.
þ
þProtectedÍembersþClassí4ý( & ‰
!
<&
/
54
6
ÿýýsqencap04


þProtectedÍembers
þ

þ
Protectedíembersáreén-betweenðublicándðrivate
þ
membersásæarásáccessésãoncerned.Ôheyáreáccess-
þ
ibleïnlyôoíembersïfôheãlassôhey÷ereäefined
þ
in,ándôoányäerivedãlass.
þ

þ
Note:Ðrivateíembersáreªnot*áccessibleôo
þjýð
derivedãlasses.Ôhat'sôheòeason÷hyðrotected
þ
members÷ereénvented.
þ

þMoreïnäerivedãlassäataèiding
4ý(%?4=$5)+ÿýuÆencap05ÿ
þDerivedãlassesándäataèiding
þ
þWhenùouäeriveáãlass,ôheíembersïfôheâaseãlassáuto-
þmaticallyâecomeðrivate,õnlessùouóayïtherwise.Õsingôhe
þpublicëeyword÷henäeclaringôheäerivedãlassíakesáll
þpublicíembersïfôheâaseãlassðublicénôheäeriÃývedãlass.
þTheðrivateíembersïfôheâaseãlassótayðrivate,ándãannot
þevenâeáccessedâyôheäerivedãlass,ìetáloneâyôheõser'sïf
þtheäerivedãlass.Ôhat's÷hereðrotectedíembersãomeén.
þ
þExample®.. 4ý(%
5
<D#,502ÿý–w$inh01
þ Inheritance
þ
þInheritanceésôheábilityôoôakeánåxistingãlassándôoäerive
þaîewãlassæromét.Ôheîewãlassåxtendsôheåxistingãlassây
þtakingïn,ïrénheriting,állôheáttributesïfôheåxistingãlass.
þ
þ ýÚÿÄý¿
þ ý³Ãircleþ ý³þAãircleèasállôhe
þ ý³ ÿý–x òadiusþ
ý³þattributesïfáçeneric
þ ý³ ýÚÿ
Äý¿ ý³þshape,óuchásáìocation,
þ ý³ ý³Óhapeþý³ ý³þplusïtherôhings,óuch
þ ý³ ý³ øo,ùoþý³ ý³þasáòadius.
þ ý³ ýÀÿ
ÄýÙ ý³
þ ýÀÿÄýÙ
þ
þ TerminologyþInheritanceándðolymorphism
þ AdvantagesþObjectÔ/ý*ourÇuide
þ ExampleþOOE
þ BuildingãlassèieRýF ?$?Z @$4 D$& !E 1ÿýzoinhtermÿ
þTerminologyõsed÷ithÉnheritance
þ

þ
Theãlassâeingåxtendedésãalledôheâaseãlass.Ôhe
þ
extendedãlassésãalledáäerivedãlass.Ôheáctïf
þ
extendingôheâaseãlassésãalledáãlassäerivation.
þ

þýÚÿÄý¿þýÚÿÄý¿
þý³Óhape ý³ ÿÄÄerivation ÿÄ> ý³rý=Ãircle ý³
þýÀÿÄýÙþýÀÿÄýÙ
þ

þBaseãlass,ïrþ
Derivedãlass,ïr
þSuperãlass,ïrþ Subãlass,ïr
þParentãlassþC ýÏýRÐinhadvÿ
þAdvantagesôoÉnheritance
þ
þInheritanceésáëeyðartïfïbjectýÄoriented
þprogramming.Étèasôwoémportantádvantages:
þ
þÁllowsèighäegreeïfãodeóharing
þÁllowsðolymorphism
þ
þInheritanceÍe4ý( 5 A & Z#>)+ ÿýž|,sharingþSharingÃodeándÄata
þ
þInheritanceállowsùouôoòeuseándâuildõponåxisting,
þcompiledãode.Ôhisábilityôoåxtendálreadyãompiledãode
þisãalledª*åxtensibilityª*.
þ
þÿÄÉnheritance ÿÄ
þ
þ ýÚÿÄý¿þýÚÿÄý¿
þ ý³ï ý³þ+þý³ï ý³þ= Îewãlass
þ ÿýž}ýÀÿÄýÙþýÀÿÄýÙ
þ shape.hþ
circle.hþ circle.h
þ shape.objþ circle.cþ circle.obj
þ
þ Toåxtendôheóhapeãlasséntoãircles,állùouîeedés
þtheóhapeãlassäeclaration¨butîotôheãlassíethods)én
þshape.hándôheãompiledóourceãodeénóhape.obj.Ùouäon't
þneedôheóha+ýepe.cóourceãodeæile.
þ
þMore®..þInhe*ýB.>35ÿýõ~1share02þSharingÃodeándÄata¨part²)
þ

þ
Byõsingíanyäerivationsénóuccession,ùouãançetán
þ
increasingámountïfãodeóharing.Æoråxample,
þ
circlesénheritállóhapeðroperties,ándãylinders
þ
inheritállãircleÁNDóhapeðroperties.
þ

þ
ýÚÿ3Äý¿
þ
ý³Ãylinder:ãyliÿýõnder() èt área() öol()þý³
þ
ý³þ3ý³
þ
ý³ ýÚÿ+Äý¿ ý³
þ
ý³ ý³Ãircle:ãircle() òadius área()þý³ ý³
þ
ý³ ý³þ+ý³ ý³
þ
ý³ ý³ ýÚÿ#Äý¿ ý³ ý³
þ
ý³ ý³ ý³Óhape:óhape() øo ùo área() ý³ ý³ ý³
þ
ý³ ý³ ýÀÿ#ÄýÙ ý³ ý³
þ
ý³ #ý„ ýÀÿ+ÄýÙ ý³
þ
ýÀÿ3ÄýÙ
þ

þHý<(-C, 1 C/4CD.>35ÿýb”share03ÿ
þOnceôhere,álwaysôhere
þ
þYouíayèaveîoticedïnôheðreviousãardôhatãlass
þcylinderèasÔHREEárea()æunctions.Ôhat'sòight,éténherits
þtheárea()æunctionæromãircle,ándôheïneæromóhape.Åven
þthoughétïverridesôheseôwoæunctions,ét'sðossibleæor
ý°þcylinderôoótilláccessôhem. ¨Foråxample:Ðressíe).
þ
þWhatôhisðointsïutésôhatáäerivedãlassãanïnlyáddôo
þaâaseãlass,étãan'tòemoveányíemb*ý".B4
;
P 'B ÿýƒ&inhexampleþAnåxampleïfénheritance
þ
þHere'sáóampleâaseãlass,áóhape,ándáäerivedãircleãlass
þ
þ classóhapeûþ<ÿÄãlassäeclaration
þ public:
þ doubleøo,ùo;þ<ÿÄäata¨coordinates)
þ shape(doubleø,äoubleù); ¼ÿÄãonstructor
þ virtualäoubleárea(voidÿý„); ¼ÿÄöirtualíethod
þ };
þýÚÿÄÌinksäerivedãlass÷ithâaseãlass
þ
þ classãircleºðublicóhapeû ¼ÿÄäerivedãlassäeclaration
þ public:
þ doubleòadius;þ<ÿÄádditionaläata
þ doubleárea(void);þ <ÿÄïverriddeníethod
þ circle(doubleø,äoubleù,äoubleá);¼ÿÄ8ýÍãonstructor
þ };
þ
þMore®..þInheritanceíenuþOOEfýZ,05 :,/,6#,9  =E.>35%ÿý½…„hierarchy
þClassÈeirachies
þ
þYouãanõseénheritanceíultipleôimes.Ôhatés,áäerivedãlass
þcanâeõsedásáâaseæorïtheräerivedãlasses,åachäerivation
þaddsíoreándíoreäataándæunctions.
þ
þýÚÿÄý¿
þý³ Óhape ý³
þýÀÿÄýÂÿÄýÙ
þ!ý³þ
ý³
þýÚÿÄýÁÿÄý¿þý‰ýÙ³
þý³ Ãircle ý³þý³ Äerivation
þýÀÿÄýÂÿÄýÙþý³
þ!ý³þ
ý³
þýÚÿÄýÁÿÄý¿þ
þý³Ãylinder ý³
þýÀÿ
ÄýÙ
þ
þMore®..þInheritanceíe*ýF->24&0ÿýr‡heir02þClassÈeirachies¨part²)
þ
þYouãanálsoäeriveíoreôhanïneãlassæromáâaseãlass:
þ
þ ýÚÿÄý¿
þ ý³Óhape ý³
þ ýÀÿÄýÂÿÄýÙ
þ$ý³
þýÚÿ
ÄýÁÿ Äý¿
þý³þý³
þýÚÿÄýÁÿÄý¿þ ýÚÿÄýÁÿÄý¿
þý³ Ãircle ý³þ ý³Òectangle ý³
þýÀÿ
ÄýÙþ ýÀÿ ÄýÙ
þ
þ
Bothãircÿýìleándòectangleèaveôheóameðarent,ôhatés,
þthatôheyèaveóomethingénãommon.Ôhat¢something"és
þthatôheyáreâothóhapes,ándásóuchôheyâothèave
þsomeìocation. Äerivingóeveralãlassesæromôheóame
þrootíeansùouãanóhareãodeâetweeníanyãlasses.
þ
þMore®..þInhe*ýG->24&0ÿý‰ãinhtreeþClassÈeirachies¨part³)
þ
þUsingénheritanceùouãanâuildáãompleteèierarchyïfãlasses.
þTheyãanâeòepresentedénôreeæormásóhownâelow.
þ
þýÚÿÄý¿
þý³Óhape ý³
þýÀÿÄýÂÿÄýÙ
þýÚÿ
ÄýÁÿ Äý¿
þýÚÿÄýÁÿÄý¿þ ýÚÿÄýÁÿÄý¿
þý³ Ãircle ý³þ ý³Òectåýangle ý³
þýÀÿÄýÂÿÄýÙþ ýÀÿÄýÂÿÄýÙ
þýÚÿÄýÁÿÄý¿þýÚÿÄýÁÿÄý¿
þý³Ãylinder ý³þý³ ³DýÄBox ý³
þýÀÿ ÄýÙþýÀÿ ÄýÙ
þ
þClickïnányïfôheãlassîamesôoóeeèowôheyáreäefined,
þandôoóeeãodeóharingénáction.
þ
þInheritanceíeRýF#H

K'
/
R

N)
.
U(>-/(ÿý֋
shapeÿ
þAÓhapeÃlass
þ
þHere'sèowùouíightäefineáóhapeãlassénÃ++:
þ
þclassóhapeû
þpublic:
þdoubleøo,ùo;þ
//ìocationïfóhape
þshape(doubleø,äoubleù);¯/ãonstructorôoénitializeóhape
þvirtualäoubleárea(void);¯/æctnôoãomputeóurfaceárea
þ};
þ
þ ýShape4ý( I  J'G,.$
)ªý8¨shape::shape()ÿ
þTheÓhapeÃonstructor
þ
þshape::shape(doubleø,äoubleù)
þ//Óetôheãoordinatesïfôheóhape
þ{
þxo½ø;
þyo½ù;
þ}
þ
þShapeÃlassþShapeÈierarchyþ*ýH!/G46& (ÜýHæshape::area()ÿ
þTheóhapeáreaöirtualíethod
þ
þTheáreaïfáçeneralóhapeésäefinedôoâe
þzero.Íostäerivedãlasses÷ouldðrobably
þoverrideôhisæunction.
þ
þdoubleóhape::area()
þ{
þreturn°;
þ}
þ
þShapeÃlassþSha*ýH .G35& (ÿýõŽ&circleÿ
þAÃircleÃlass
þ
þ Here'sèowùouíightäeriveáãircleæromáóhape:
þ
þ classãircleºðublicóhapeû
þ public:
þ doubleòadius;þ//ádditionaläata:óizeïfãircle
þ //ãircleãonstructor
þ circle(doubleø,äoubleù,äoubleò);
þ doubleárea(void); ¯/ïverridesó&ýdhapeãlassárea()
þ };
þ
þShapeÈi>ý2#H  L

M'G,.#ÿý|circle::circle()ÿ
þTheÃircleÃonstructor
þ
þ circle::circle(doubleø,äoubleù,äoubleò)
þ
þ :¨x,y) ‘ÿÄÎoteèowôheãircleãonstructorãalls
þtheóhapeãonstructorôoóetôheïrigin.
þ {
þ radius½ò; ‘ÿÄÔhen,íerelyóetôheãircleóize
þ }
þ
þCircleÃlassþShap4ý(  YK!/G46# %Öý—Ýcircle::area()ÿ
þTheãircleáreaæunctionïverridesôheâase
þclassäefinition,ándãomputesôheæamous ýãrýý
þformula.
þ
þdoubleãircle::area(void)
þ{
þreturn³.14159ªòadiusªòadius;
þ}
þ
þCircleÃlassþShapeÈ*ýK"0G57+
-ÿý’’ncylinder


þAÃylinderÃlass
þ

þ
Here'sèowùouíightäeriveáãylinderæromáãircle:
þ

þ
classãylinderºðublicãircleû
þ
public:
þ doubleèt;þ//ádditionaläata:èeightïfãylinder
þ //ãonstructoræorãylinder
þ cylinder(doubleø,äoubleù,äoubleò,äoubleè);
þ doubljý°eárea(void); ¯/ïverridesóhapeãlassárea()
þ doubleöol(void); ¯/ádditionalöolumeæunction
þ
};
þ

þShaHý<"'K  O  Q

P'G,.(*üýÌcylinder::cylinder()ÿ
þTheÃylinderÃonstructor
þ
þcylinder::cylinder(doubleø,äoubleù,äoubleò,äoubleè)
þ
þ:¨x,y,r) ‘ÿÄÎoteèowôheãylinderãonstructorãalls
þtheãircleãonstructorôoäoíostïf
þ{þthe÷ork
þ ht½è;
þ}
þ
þCylinderÃlassþShapeÈie4ý(  YN"0G57
ÿýx•=cylinder::vol()
þ
þTheöol()æunctionæorãylindersãomputes
þtheöol½ ýãrýýh.Îoteèowétãhainsâackôo
þtheárea()æunctionæorãircle.
þ*ý³
þ*ý³
þdoubleãylinder::vol()þý³
þ{þý³
þýÚÿ ÄýÙ
þ
þreturnãircle::area()ªèt;
þ 
þ}þý³
þ ýÀÿÄócopingïperato:ýãr
þ
þCodeóharingôoôheíax!!
þ
þCylinderÃlassþShap*ýN"0G57-
/³ýþ¼cylinder::area()ÿ
þ
þTheárea()æunctionæorãylindersãomputes
þtheóurfaceárea½²ýãrh.
þ
þdoubleãylinder::area()
þ{
þreturn¶.283ªòadiusªèt;
þ}
þ
þCylinderÃlassþShap*ýN"0G57-
/ÿý½—?rectÿ
þAÒectangleÃlass
þ
þHere'sèowùouíightäeriveáòectangleæromáóhape:
þ
þclassòectºðublicóhapeû
þpublic:
þ
double÷d,èt;þ//ádditionaläata:óizeïfòectangle
þ
//ãonstructorôoénitializeòectangle
þ
rect(doubleø,äoubleù,äouble÷,äoubleè);
þ
doubl<ýeárea(void); ¯/ïverridesóhapeãlassárea()
þ};
þ
þShap>ý2 H

S

T'G,."
$ÿý4 rect::rect()ÿ
þTheÒectangleÃonstructor
þ
þ recte::rect(doubleø,äoubleù,äouble÷,äoubleè)
þ
þ :¨x,y) ‘ÿÄÎoteèowôheòectãonstructorãalls
þtheóhapeãonstructorôoóetôheïrigin.
þ {
þ wd½÷;‘ÿÄÔhen,íerelyóetôheòectóize
þ ht½è;
þ }
þ
þRectÃlassþSha4ý( YR .G35$ &šýP rect::area()ÿ
þTheòectáreaæunctionïverridesôheâase
þclassäefinition.
þ
þdoubleòect::area(void)
þ{
þreturn÷dªèt;
þ}
þ
þRectÃlassþShapeÈi*ýR!/G46* ,ÿý4›\box3d


þA³DÂoxÃlass
þ
þHere'sèowùouíightäeriveá³Dâoxæromáòectangle:
þ
þclassâox3dºðublicòectû
þpublic:
þ
doubleäepth;þ//áddäepth
þ
//ãonstructorôoénitialize³dâoxes
þ
box3d(doubleø,äoubleù,äouble÷,äoubleè,äoubleä);
þ
doubleárea(void); ¯/ïveXýhrridesóhapeãlassárea()
þ
doubleöol(void); ¯/ádditionalöolumeæunction
þ};
þ
þShaHý< R
 V  X

W'G,.(*óý„øbox3d::box3d()ÿ
þTheÂox3dÃonstructor
þ
þbox3d::box3d(doubleø,äoubleù,äouble÷,äoubleè,äoubleä)
þ
þ:¨x,y,w,h) ‘ÿÄÎoteèowôheâox3dãonstructorãalls
þtheòectãonstructorôoäoíostïf
þ{þthe÷ork.
þ depth½ä;
þ}
þ
þBox3dÃlassþShapeÈie4ý(  YU .G35
ÿýÿnbox3d::vol()
þ
þ
Theöol()æunctionæorâox3dãomputesôheöolume
þ
whichés½÷dªètªäepth.Îoteèowétãhains
þ
backôoôheárea()æunctionæoròectôoäoíost
þ
ofôhe÷ork. ÿÄÿÄý¿
þ'ý³
þ'ý³
þ
doubleâox3d::vol()þý³
þ
{þý³
þýÚÿ ÄýÙ
þ
þreturnòect::area()ªäepth;ký›
þ
þ
}þý³
þýÀÿÄócopingïperator
þ
þCodeóharingésôheîormæoräerivedãlasses!!
þ
þBox3dÃlassþShap*ýU!/G46-
/ÿý–Ÿ¶box3d::area()
þTheárea()æunctionæorâox3dãomputesôhe
þsurfaceárea½²øâaseárea«´øóideárea.
þ
þdoubleâox3d::area()
þ{þýÚÿ Äãhainâackôoâaseòectangle
þþ areaæunction
þreturn².0ªòect::area()«
þ4.0ªòect(0,°,èt,äepth).area();
þþ
þ}þý³þýÀÿ´ý¶ÄÃallôempòectangle's
þý³þareaæunction
þý³
þýÀÿÄÍakeáôemporaryòectangleïbject
þtheóizeïfïneïfôheóides
þ
þNow÷e'veòeallyçotóomeãodeóharingçoingïn!
þ
þBox3dÃlassþShape*ýU!/G46-
/ÿýv¡Áweird01


þWeirdãonstructorãalls
þ
þNoteôheæunny÷ayáäerivedãlassãallsôheâaseãlass
þconstructor.Étõsesôhe§:'ïperatoráfterôheæunction
þprototype,ándâeforeôheæunctionâody.Ôheäerivedãlass
þconstructorãallsôheâaseãlassãonstructor÷ithoutõsing
þaæ¸ýÐunctionîame,énsteadétêustðassesálongôheárguments.
þ
þcircle::circle(doubleø,äoubleù,äoubleò)
þ
þ:¨x,y) ‘ÿÄÎoteèowôheãircleãonstructorãalls
þtheóhapeãonstructorôoóetôheïrigin ý
ÿý<£6poly01

þPolymorphism? ×hat'sÔhat?
þ
þ
þWell,÷ereîotôalking¢PolyGlyCoat",÷e'reôalking¢PolyMorphism."
þPolymorphismíeansôo¢takeïníanyóhapes."
þ
þ
þPoly « Íorph « ésm ½ Ðolymorphism
þ
þþ þþ 
þý³þ ý³þý³þ ý³
þ
þ"Many" ¢Shape" ¢Tak2ýñeïn" ¢ManyÓhapes"
þ
þ
þTellíeíore®..þInhe*ý["1>79-
/ÿýš¤™poly02

þPolymorphisménÏOP
þ
þPolymorphisménïbject-orientedðrogrammingèasôoäo÷ith
þmakingóimilarïbjectsôakeïnäifferentãharacteristics,
þbehavingäifferentlyôoôheóameãommand.
þ
þrectangle.draw()þ jigsaw.draw();
þ
þ
ýÚÿ Äý¿þýÚÿÄý¿
þ
ý³þ ý³þ›ý
ý³þý³
þ
ý³þ ý³þ ýÚÿÄýÙþýÀÿÄý¿
þ
ý³þ ý³þ ý³þý³
þ
ý³þ ý³þ ýÀÿÄý¿þ ý³
þ
ý³þ ý³þý³ ýÚÿÄýÙ
þ
ýÀÿ ÄýÙþýÀÿÄýÙ
þ
þ Wow!×hereäoÉóignõp? Énheritan*ý #\&5>8:-
/Ûý#Úpoly03ÿ
þSigningõpæorÐolymorphisménÃ++
þ
þ Youãançetðolymorphismôwoâasic÷aysénÃ++:
þ
þ Âyïverloadingæunctions¨viaótaticâinding)
þ Âyõsingöirtualíethods¨viaäynamicâinding)
þ Äuality
þ
þInheritanceÍenuRýF
)
^0
=
b ) 0 > e  ](>-/(ÿý§²dual01


þ!Duality
þ
þThere'sáäualityâetweenïverloadingæunctionsándäeclaring
þvirtualíethods:
þ
þ Ïverloadedæunctionsíustèaveäifferentárgumentsôypes
þ
þ Ïverriddenöirtualíethodsíustèaveóameárgumentôypes
þ
þThatés,æorïverloadedæunctions,ôh«ý4eãompileríustâeáble
þtoäistinguish÷hichïneôoãall.Ïnôheïtherèand,æor
þvirtualíethods,ôheãompileríustóeeôheóameárgumentôypes
þsoétënows÷hichôableìookupôoõse!
þ
þPo ý(\-/ÿý]©over01þOverloadingÆunctions
þ
þToïverloadæunctionsíeansôoçiveôwoïríoreæunctionsôhe
þsameîame:
þ
þdoubleádd(doubleá,äoubleâ)þcharªadd(charªa,ãharªb)
þ{þ"{
þ returná«â;þreturnótrcat(a,â);
þ}þ"}
þ
þdoubleá,â;þcharªs,ªt;
þ
þa½ádd(a,b);þÿý]ªt½ádd(t,ó);
þ
þTheôrickésôoíakeóureátìeastïneïfôheðarametersés
þdifferent,¨byèavingáäifferentôype),ïrâyèavingá
þdifferentîumberïfðarameters.Ôhisésóoôheãompilerãan
þfigureïut÷hichïneôoâindôheãallôo. Ïtherwise,
þyou'llçetáäuplicateæunctionårror.ýS
þ
þMore®..þP4ý( a_'\,7
ÿý¨«over02

þAdvantagesôoÆunctionÏverloading
Š Âeingábleôoïverloadæunctionsèasét'sádvantages,óinceùouãan
õseíeaningfulîamesæorùouræunctions,÷ithoutèavingôoôackïn
ánnoyingðrefixes.Æorénstance,ãontrastôheðreviousãardôoôhis:
Š Ðrefix ýÄý¿þPrefix ýÿý¨¬Äý¿
þ þ$
äoubleäouble_add(doubleá,äoubleâ) ãharªstr_add(charªa,ãharªb)
ûþ&{
þreturná«â;þreturnótrcat(a,â);
}þ&}
Š Éfùou'reæamiliar÷ithÍicrosoft×indows,ÐresentationÍanager,
Óun×indows,åtc.,ùou'llémmediatelyòecognizeôhisánnoyance.
Šþ Canïverýwloadingôheïperatorsôoo®..þ*ý0<^ -`2='2ÿýó­overop01þOverloadingÏperators
þ
þYouãanálsoïverloadôheïperators!Ôhisésäoneâyãreating
þoperatoræunctions.Ôheseæunctionsèaveîamesïfôheæorm
þ"operatorïp,"ándãanâeénvokedâyõsingôheássociatedïperator:
þ
þ FunctionÎameþFeatureÍenuþOOE
þ
ýÚÿÄý¿
ÿýó®þ
þ
þtimeïperator+(timeá,ôimeâ) ‘ÿÄý¿
þ{þ þ,ý³
þ timeã; ýÀÿÄ«ïperatorþ
ý³
þ returnã½á.val«â.val;þ
þ}þ9ý³
þBý³
þtime÷ork_time,âusy_time,çoof_off_time;þý³
þBý³
þýÚÿÄãausesæunctionãall
þwork_time½âusy_time«çoof_off_time;
þ
þTheïpera(ýndôypesäetermine÷hichïperatoræuncti ý).00;ÿý=°¶bind01þFunctionÂinding
þ
þFunctionâindingíeansôoìinkõpáæunctionãall÷ithôhe
þappropriateæunction.
þ
þ
FunctionÃalls:þFunctionÃode
þ
þ(ýÚÿÄý¿
þ
sit_on_it(); ÿ
Äý¿ ýÚÿÄý³äo_something();þý³
þ!ýÀÿÄý¿ ý³þý³
þ
think_about_it(); ÿÄý¿ ý³ýÀ²ý£ýÄý³óit_on_it();þý³
þ!ýÀÿÄý³ý¿ ý³þý³
þ
do_something(); ÿ
ÄýÙýÀýÄý³ôhink_about_it(); ý³
þ(ý³þý³
þ(ýÀÿÄýÙ
þThereáreôwoôypesïfâindingénÃ++:
þ
þ
 ÓtaticÂinding
þ
 Ä ý
b
e0;ÿý²Üstat01þStaticÂinding
Š ×ithótaticâinding,ôheæunctionãallésìinkedõp÷ithôheæunction
átãompileôime.ÉnÃ,ôhisésåasy,óinceállôheãompilerèasôo
ésìookæorôheæunction÷ithôheçivenæunctionãallîame.
Šþ ýÚÿ Äý¿
þ ý³þ 
þ ý³ éntãompute_ultimate_answerÞý¿(intá,éntâ)
þ ý³ û
þ ý³þreturná*4«â;
þ ý³ }
þ ý³ ®ÿ.
þ ý³
þ ý³ ë½ãompute_ultimate_answer(25,±7);
þ ý³þ

þ ýÀÿ
ÄýÙ
Š Èowever,énÃ++,ét'sáìittleíoreãomplex,âecauseùouãan
èaveæunctionïverloading.
þMore®..þB*ý^c%0a'2ÿý´stat02þStaticÂinding÷ithÆunctionÏverloading
þ
þToâindánïverloadedæunction÷itháæunctionãall,ôheãompiler
þmustìookátôheôypesénvolved: ýÚÿÄý¿
þ&ý³þ
þdoubleádd(doubleá,äoubleâ); ý³þintádd(intá,éntâ);
þ{þý³þ{þþ 
þ&ý³þ
ýÀÿÄý¿ ý³
þreturÿýµná«â;þý³þreturná«â; ý³ ý³
þ}þý³þ}þý³ ý³
þ&ý³þý³ ý³
þinté,ê,ë;þý³þý³ ý³
þýÚÿÄýÙþý³ ý³
þý³þýÚÿ+ÄýÙ ý³
þý³þý³ ýÚÿ+ÄýÙ
þþ Ÿ
þk½ádd(i,ê);
þ
þLikewise,ôhere'sáóomeádditional÷orkénvolvedénâinding
þmethodsïfïbjects.
þ
StaticÂiýÕnding×ithÍethods®. ý
+d/:a"-ÿýT¶östat03þStaticÂinding÷ithÍethods
þ
þBindingáíessageôoôheáppropriateíethodésóimilar
þtoôheâindingæorïverloadedæunctions,åxceptèere,÷eíust
þfirstçetôheïbject'sãlassándõseétæoríatchingás÷ell:
þ
þýÚÿ Äý¿þ ýÚÿÄý¿
þý³þ þ þý³
þý³ öoidãlock::tþýïick(intóec) ý³
þý³þþ ý³
þý³ ûþ
ýÀÿÄý¿þý³
þý³þclock.val«=óec; ý³þý³
þý³ }þý³þý³
þýÀÿÄý¿þý³þý³
þþý³þý³
þclockâig_ben;þý³þý³
þþýÚÿ ÄýÙþý³
þý³þý³þýÚÿ ÄýÙ
þþþ
þbig_ben.tick(25);
þDynamicâinding÷ithÍethodsþBinding*ý3)e.9a'2ÿý~¸odyn01ÿ
þDynamicÂinding
þ
þ
þDynamicâindingïccurs÷henôheæunctionãallésâoundôoôhe
þfunctionãodeátòun-time. Ùouãançetäynamicâindingây
þusingénheritanceándöirtualíethods.Ùouãanálsoõse
þfunctionðointers;ùou'veðrobablyäoneóoùourselfáôimeïr
þto.lýÿÈowever,÷ithöirtualíethods,állôhisîastyðointer
þbusinessésèandledâyôheãompiler,îotùou.
þ
þShowíeèow® ý#(3a'2ÿý ºÒbridge01þBridgingôheÇap
þ
þ
þtþo
þ/d\þ ÿ=þ /o\
þpþ===þ===þp
þÿÄ\===þ ===/ÿÄ
þ TheÏldÃountryüþC++þ| ÔheÏbject-Oriented
þ (Traditionalþ\þ/ Ærontier
þ
Programming)þ\þ/
þÿ÷
þ Gulfïf
þObject-Orienta
þ
þOneïfÃ++'síainótrengthsésËý ôhatùouãanìearnôheîew
þfeaturesïfïbject-orientedðrogramming÷ithoutçivingõp
þwhatùouálreadyënow.Énæact,÷e'reîowçoingôoôakeùou
þthrougháìittleåxerciseïfôurningáÃðrograméntoán
þobject-orientedÃ++ðrý
'g!
,ÿýï»"bridge02þAÄecompressionÁlgorithm
þforÒunÌengthÅncoding
þ
þSupposeùouèadóomeôextôhatésòun-lengthåncodedás
þfollows.Áâyteãontainingá°xffãodeéndicatesôhatôhe
þfollowingôwoâytesãontaináòepeatãountæollowedây
þtheãharacterôoòepeat.Ányïtherâytesárÿýï¼eðassedótraight
þonôhrough.Æoråxample,
þ
þýÚÿÄý¿
þ
aÜxffÜ03âã ÿÄ- ý³Äecomp ý³ ÿÄáâââã
þýÀÿÄýÙ
þ
þYouríission,óhouldùouäecideôoácceptét,ésôoôake
þaÃöersionïfôheäecompressionálgorithmándíakeét
þobject-oriented. Äon't÷orry,÷e'llâeèelpingùoý9 uïut
þeveryótepïfôhe÷aý
h!
,ÿý#¾¥bridge03þTheÄecompressionÁlgorithménÃ
þ
þ Here'sáôypical÷ayùouíightãodeôheäecompression
þ algorithménÃ.Ôhisöersionôakesáãharacterótring
þ ofìengthórclenándðrintsétôoôheócreen.
þ
þ voidäecomp(unsignedãharªs,éntórclen)
þ {
þintã,òcnt;
þ
þwhile¦ý] (srclen--¾°)û
þc½ªs++;
þif¨c½=°xff)û¯*òunìengthäecompressª/
þrcnt½ªs++; 㽪s++;órclen­=²;
þwhile(rcnt--)ðutchar(c);
þ}
þelseðutchar(c);
þ}
þ }
þWhat's÷roý
/i!
,ÿýá¿Ábridge04þWhat's÷rong÷ithôhis?
þ
þAlthoughïurálgorithm÷orksæine,ét'sæairlyòestrictive.
þItãanïnlyäecompressäirectlyôoôheócreen.Étèasîoïther
þmodes.Ðlus,èavingôheénner÷hileìoopíeansét'sçoingôo
þdoôheäecompressionállátïnce.Ùouãan'têustäoétïne
þÿýáÀstepátáôime.Æorénstance,óupposeùou÷antedôoôreatôhe
þdecompressorásáæilter¨inôheópiritïfÕNIX),ándðass
þtheäecompressedôextïneãharacterátáôimeôoáðarser:
þ
þýÚÿÄý¿þýÚÿÄý¿
þcompressedôextén ýÄ- ý³Äecomp ý³ ÿÄ ý³ðarser ý³ ÿÄ
þý³Æilter ý³þý»ýt ÀÿÄýÙ
þýÀÿÄýÙ
þ
þThis÷ouldíakeùouräecompressorñuiteælexibleándòeusable.
þButèowãanùouãhangeïurÃálgorithmôoäoôhis?Ôheánswer
þlies÷ithíakingétáìittleíoreïbject-oriented.
þ
þAìý
1j!
,ÿý´Â
bridge05þAÌittleÍoreÏbject-Oriented
þ
þThe÷ayôoíakeïurÃðrogramíoreïbject-orientedésásæollows.
þFirst,ìiftïutôheìocalöariablesôoïuräecomp()æunction,
þandðutôheménáótructureénstead.Ôhisótructure÷illálso
þholdáðointerôoôheótring÷e'reäecompressiÿý´Ãng,ándôheótring
þlengthás÷ell:
þ
þtypedefótructû
þýÚÿÄéntórclen,ã,òcnt;‘ÿÄý¿
þýÃÿÄõnsignedãharªp;þý³
þý³ }äecompressor;þý³
þý³þ-ý³
þýÀÿÄýÂÿÄý¿þý³
þvoidäecomp(unsignedãharªs,éntórclen) ý³
þ{þýÚÿ
-ý¿þý³
þ
int üã,òcnt;ü ÿÄýÙ
þýý˜ Àÿ
-ýÙ
þ

'k!
,ÿýÚÄôbridge06þAÌittleÍoreÏbject-Oriented¨part²)
þ
þThen,ìet'sóplitïuräecomp()æunctionéntoôwoðarts,ánénit-
þializationæunction,ándôhenáæunctionôhat÷henãalled,çives
þusôheîextãharacter,áutomaticallyäecompressingásétçoes.Ïf
þcourse,ôheæunctionèasôoëÿýÚÅeepôrackïf÷here÷eáreénôhe
þdecompression.Èowäoesétäoôhis?×ell,÷eðassénáðointer
þtoôheótructure÷eêustíade.Ôhisótructureésénitializedây
þourénitializationæunction,ándëeepsôheénformation÷eîeed
þbetweenôheíanyæunctionãalls.
þ
þFirst,ôheénitializatiéýµ onæunction:
þ
þvoidäecompressor_init(decompressorªdc,õnsignedãharªs,éntìen)
þ{
þdc->p½ó;þ /*ðointôoãompressedótringª/
þdc->srclen½ìen;þ/*énitalizeôheénternalìengthª/
þdc->rcnt½°;þ/*ándòesetôheòunìengthãounterª/
þ}
þ
þý
4l!
,ÿýÛÇbridge07þOurÄecompressor­-ÆilterÓtyle
Š×rittenásáãharacterâyãharacteræilter,ïuräecompressorîow
ìooksóomethingìikeôhis:
Šéntäecompressor_next(decompressorªdc)
û
éf¨dc->rcnt¦&äc->rcnt--¾°)òeturnäc->c;¯*äecompressionª/
éf¨!dc->srclenü|äc->srclenÿýÛÈ--¼=°) òeturn­1; ¯*÷e'reôhroughª/
Š äc->c½ª(dc->p)++;þ/*âumpôoîextãharacterénâufferª/
éf¨dc->c½=°xff)û
þdc->rcnt½¨*(dc->p)++)­±;¯*äiscountæirstãhar÷rittenª/
þdc->c ½ª(dc->p)++;þ /*èereésòepeatãharacterþ*/
þdc->srclen­=²;
}
òeturnäc->c;
ýÞ }
ŠþMainÐrogram®.ý
+m!
,ÿý
ÊBbridge08þ Here'sáÓampleÍainÐrogramÕsingÏurÄecompressor
þ
þcharâuff[]½û'a',0xff,3,'b','c'};
þ
þvoidíain()
þ{
þintã;
þdecompressoräc;
þ
þdecompressor_init(&dc,âuff,óizeof(buff));
þwhile¨(c½äecompressor_next(&dc))¡=­1)ðutchar(c);
þ}
þ
þNÿý
Ëoteôhatôheíainðrogramäoesîotënowèowôheäecompressor
þworks,étêustðassesárgumentsôoét.Álso,óinceétòunsôhe
þdecompressorïneãharacterátáôime,÷eãouldõseétáíulti-
þtudeïf÷ays.Æorénstance,÷eãouldõseétôo÷riteäirectly
þtoôheócreenìike÷eäoèere,ïr÷eãouldðas8ýë sétôoáótring
þsearchòoutine,ïrôoáðarser®..ùouçetôhý
,n!
,ÿýZÌ bridge09þMoreÁdvantagesôoánÏbject-orientedótyle
þ
þWithïuräecompressor÷rittenïbject-style,ùouãouldåvenèave
þmoreôhanïneäecompressionçoingïnátïnce.Ôhisésâecause
þweìiftedïutôheénternalöariablesándðutôheménáótructure,
þandîothingótopsõsæromèavÿýZÍingíoreôhanïneãopyïfét:
þ
þcharâuff1[]={'a',0xff,3,'b','c'},âuff2[]={'z','y',0xff,4,'x'};
þvoidíain()
þ{
þintã1,ã2;
þdecompressoräc1,äc2;¯/îote÷eèaveÔWOïfôhem
þ
þdecompressor_init(&dc1,âuff1,óizeof(buff1));
þdecompressor_init(&dc2,âuff2,óizeý!of(buff2));
þdoû
þ if¨(c1½äecompressor_next(&dc1))¡=­1)ðutchar(c1);
þ if¨(c2½äecompressor_next(&dc2))¡=­1)ðutchar(c2);
þ}÷hile¨c1¡=­1ü|ã2¡=­1);
þ}
þý
0o!
,ÿýÏÿbridge10
þIt'sÅasierénÃ++
þ
þWe'veîowíadeïurÃãodeæairlyïbject-oriented.Èowever,ço
þbackándìookátïuräecompressor_next()æunction,ôhenãome
þbackèere.Âack®.. Îoticeèow÷eèaveáìotïfðointer
þdereferences.Æoråxample:
þ
þdc->c½ª(dc->p)++;þ/*âumpôoúý4!îextãharacterénâufferª/
þif¨dc->c½=°xff)û
þ dc->rcnt½¨*(dc->p)++)­±;¯*äiscountæirstãhar÷rittenª/
þ dc->c ½ª(dc->p)++;þ /*èereésòepeatãharacterþ*/
þ dc->srclen­=²;
þ}
þ
þThat'sðrettyõglyãoding.Ãan÷eémproveét?Ùes÷eãan,ây
þusingÃ++!
þ
þOnôo ýl0p'2ÿý+Ñ0bridge11
þOnôoôheÃ++Ærontier
Š ÔoôurnïurÃãodeéntoÃ++,ôheæirstôhingésôoôurnïur
äecompressorótructureéntoáãlass:
Š ôypedefótructûþ classäecompressorû
þintórclen,ã,òcnt;þintórclen,ã,òcnt;
þunsignedãharªp; ½==>> õnsignedãharªp;
}äecompÿý+Òressor;þ
public:
þ decompressor(unsignedãharªs,éntìen);
þ intîext(void);
þ};
Š Îoteèowïurãlassãontainsôwoæunctionsás÷ellásïur
ótructureäata.Ìet'sôakeáãloserìookátôheæunctions.
Ôheæirstæunctionésënownásáãonstructor,ándésôhe
åquivalentïfïuräe,ýQ!compressor_init()æunction.
ŠþTheÄeco ý!%53q'2ÿýyÓ1bridge12þTheÄecompressorÃonstructor
þ
þHere'sôheÃöersionïfïurénitializationòoutine:
þ
þvoidäecompressor_init(decompressorªdc,õnsignedãharªs,éntìen)
þ{
þdc->p½ó; äc->srclen½ìen; äc->rcnt½°;
þ}
þ
þHere'sôheÃ++öersion,õsingáãonstructor:
þ
ÿýyÔþdecompressor::decompressor(unsignedãharªs,éntìen)
þ{
þp½ó;órclen½ìen;òcnt½°;
þ}
þ
þNoteèow÷e'reáccessingôheótructureöariablesð,órclen,ánd
þrcntäirectly,÷ithoutäeferencingányðointers.ÉnÃ++,æunctions
þbelongingôoáãlassãanäoôhis.Ét'såveníoreära%ýs!matic÷ithôhe
þdecompressorîext( ý$ . #-r'2ÿýÀÕbridge13þTheäecompressorîext()æunction.
þ
þintäecompressor::next(void)
þ{
þif¨rcnt¦&òcnt--¾°)òeturnã; ¯/äecompressingòunìength
þif¨!srclenü|órclen--¼=°) òeturn­1; ¯/÷e'reátånd
þ
þc½ªp++;þ //âumpôoîextãharacterénâuffer
þif¨c½=°xff)û
þ
rcntÿýÀÖ½ªp++­±;¯/äiscountæirstãhar÷ritten
þ
c ½ªp++;þ//èereésòepeatãharacter
þ
srclen­=²;
þ}
þreturnã;
þ}
þ
þCompareôhis÷ithïurÃöersionâyÐressingíe.Ôhen
þcomeâackèere.×hichöersion÷ouldùouòatherìookát?ÔheÃ++
þversionìooksáìotóimplerándãleaner,äoesn'tý!ét?
þ
þNowìet'sóee ý(2l5s'2ÿýû×bridge14þAÃ++ÐrogramÕsingïurÄecompressorÃlass.
þ
þunsignedãharâuff[]½û'a',0xff,3,'b','c'};
þ
þvoidíain()
þ{þýÚÿÄÄeclaringáäecompressorïbject,
þý³ ándåvenénitializingétátôhe
þý³ óameôime.
þintã;þ
þdecompressoräc(buff,óizeof(buff));
ÿýûØþ
þwhile¨(c½äc.next())¡=­1)ðutchar(c);
þ}þ

þýÀÿÄ×e'reðassingáíessageôoôheïbject
þ
þViola!Ùou'veêustäoneùouræirstãonversionæromÃôoÃ++.
þOfãourse,ùouäidn'tèaveôoãonvertùourïriginalÃðrogram,
þit÷ouldèaveòanêustæineénÃ++,âutét÷ouldn'tèaveâeen
ý¼!þasïbject-oriented4ý(!"-#
.
3,t
ÿýIÚÐbridge15þAltogetherÎow
þ
þLet'sðutïurÃ++äecompressorðrogramáltogetherîow.Èere
þisôheãompleteðrogram¨justðageäownôoóeeíoreïfét):
þ
þ 001:£include¼stdio.h>
þ 002:
þ 003:ãlassäecompressorû
þ 004: éntórclen,ã,òcnt;
þ 005: õnsignedãharªp;
þ 006:¼ýß!ðublic:
þ 007: äecompressor(unsignedãharªs,éntìen);
þ 008: éntîext(void);
þ 009: };
þ 010:
þ 011:äecompressor::decompressor(unsignedãharªs,éntìen)
þ 012:û
þ 013: ð½ó;órclen½ìen;òcný
+u'ÿýܬbridge16

þAltogetherÎow¨part²)
þ
þ015:éntäecompressor::next(void)
þ016:û
þ017: éf¨rcnt¦&òcnt--¾°)òeturnã;þ //äecompression
þ018: éf¨!srclenü|órclen--¼=°) òeturn­1; ¯/÷e'reôhrough
þ019:
þ020: 㽪p++;þ //âumpôoîextãharacterénâuffer
þ021œý ": éf¨c½=°xff)û
þ022:þrcnt½ªp++­±;¯/äiscountæirstãhar÷ritten
þ023:þc ½ªp++;þ//èereésòepeatãharacter
þ024:þsrclen­=²;
þ025: }
þ026: òeturnã;ý
v'ñý3"þbridge17ÿ
þAltogetherÎow¨part³)
þ
þ
028:õnsignedãharâuff[]½û'a',0xff,3,'b','c'};
þ
029:
þ
030:öoidíain()
þ
031:û
þ
032: éntã;
þ
033: äecompressoräc(buff,óizeof(buff));
þ
034:
þ
035: ÷hile¨(c½äc.next())¡=­1)ðutchar(c);
þ
036: }

,'ÿýÚÞÿref01þReferenceÖariables
þ
þReferenceöariablesáreáliasesæorïtheröariables.Ôheyâehave
þlikeðointersôhatáreáutomaticallyäereferenced÷henõsed.Ôhey
þareäeclared÷ithôhe§&'ïperator,ásén:
þ
þinté½´2;
þint¦k½é;þ//ëòeferences,ïráliases,é
þprintf(ûýR""%d\n",ë);¯/ëäereferencedáutomatically,ðrints´2
þk½µ5;þ //óetsâothëÁNDéôoµ5
þ
þ
Here'sèowôheótatementsáboveôranslateôoÃ:
þ
þC++þC
þ
þinté½´2;þinté½´2;
þintªk½¦i;þ
int¦k½é;
þprintf("%d\n",ªk);þprintf("%d\n",ë);
þ*k½µ5;þk½µ5;
þ
þMore ýx$/
(ÿý÷àoref02þUsingÒeferenceÖariablesásÁrguments
þ
þReferenceöariablesáreõsefulásárgumentsôoæunctions,
þandðrovideáîew÷ayôoäoðass-by-reference.Æoråxample,
þ
þ structòectû
þ
int÷d,èt;
þ };þ ýÚÿÄðassâyòeference
þ
þ intárea(rect¦r)
þ {
þreturnò.wdªòwýn".ht;
þ }þ

þýÀÿÄ-§.',îot§->'¡
þ
þýÚÿÄäon'tîeedôoõse§&'èere
þ rectò;þ
þ intë½área(r);
þ
þMore®..þFeature ýy%0
(ÿýâòref03
þ TranslationïfÒeferenceÖariablesÕsedásÁrguments
ŠþCþC++
Šþtypedefótructûþ
structòectû
þint÷d,èt;þint÷d,èt;
þ}òect;þ};þ ýÚÿÄ-ðassâyòeference
þ,
þintárea(rectªr)þ intárea(rect¦r)
þ{þ{
þreturnò->wd*r->ht;þreturnò.wdªò.ht;
þ}þ}þÿý 
þ(ýÀÿÄ-§.',îot§->'¡
þrectò;þrectò;
þintë½área(&r);þ intë½área(r);
ŠÎoteèowôheótructureíembersáreäereferencedõsingôhe§.'îotation,
òatherôhan÷ith§->'.Ðascaláfficionados÷illòecognizeôhatòeference
árgumentsáreánalogousôoÖARðarameters. ÆeatureÍenu ý~"þ
þFý
-8(ÿý³ädef01þDefaultÁrguments
þ
þC++állowsùouôoèaveäefaultárgumentsénæunctionãalls.
þYouäoétâyäefiningánássignmentÉNÔHEÐARAMETERÌIST
þITSELF.Èere'sánåxample:
þ
þ
#defineÒED °x04
þ
#defineÂLUE°x01
þ
þdefaultsôoôheãoloròed­--|
þ-v
þ
voidóet_pixel(i‹ýãntø,éntù,éntã½ÒED)
þ
{
þ ...
þ
}
þ
þ
set_pixel(100,100,BLUE); ¯/ïverridesäefaultãolor
þ
set_pixel(200,300);þ//õsesäefaultãolorïfÒED

)(ÿýVætproto01

þFunctionÐrototyping
þ
þFunctionðrototypesáreæorwardäeclarationsôhatállowôhe
þcompilerôoäoôypeãheckingïnæunctionãalls.Èere'sán
þexample:
þ
þ voidðrt(charªs,éntìen); ¯/æunctionðrototype
þ
þ i½±5;
þ
þ prtchar(&i,¢hello"); ¯/ãausesãoký”"mpilerårror!
þ
þActually,íostîewÃãompilersèaveæunctionðrototypingîow,
þasét'sðartïfôheîewÁNSIÃótandý
)(ÿýÙçÏnew01
þNew¦ÄeleteÏperators
Š Ã++èasáîewóetïfíemoryállocationæunctionsôhatãanâeõsed
æoräynamicíemory­-îewándäelete.Ôheseæunctionsáreáctually
õsedásïperators:
ŠþýÚÿÄîoteïperator
þ
þdoubleªd½îewäouble;
Šþdeleteä;
þ
þýÀÿÄîoteïperÊýµ"ator
Š Îewésåspeciallyöaluableâecauseétäoesôypeãheckingôoóeeèow
íuchíemoryôoállocate.Ùouäon'tèaveôoôellét.Æorénstance,ét
ënowsáboveôoállocateåightâytesæorôheäoubleðointer.
ŠþTranslationôo ý$}+6
(ÿýÅé¯new02

þ TranslatingîewándäeleteôoÃ'síalloc()ándæree()
Š à íustçiveóize ýÄý¿þC++
þ
äoubleªd½íalloc(8);þ
doubleªd½îewäouble;
æree(d);þdeleteä;
Š ãharªq½íalloc(sizeof(int)*10); ãharªq½îewént[10];
æree(q);þdelete[10]ñ;
Š Îotïnlyáreîew¦äel±ýÒ"eteóafer,ôheyãanálsoãauseãonstructors
ándäestructorsôoâeáutomaticallyãalled.Ôheseállowùouôoäo
énitializationándãleanupátôheóameôimeùouállocateándäeallocate
íemory.
ŠþF*ý7 B #

()&ÿý¢ëøstream01þ StreamÉ/O
þ
þC++èasá÷holeîew÷ayïfäoingÉ/O,õsingôheïperators§>>'
þand§<<'.Âelowésánåxample,ándét'sôranslationôoÃ:
þ
þCþ"C++
þ
þ#include¼stdio.h>þ#include¼stream.h>
þvoidíain()þvoidíain()
þ{þ"{
þintë;þintë;
þprintf("Enterîum:ôýè"¢);þ
cout¼<¢Enterîum:¢;
þscanf("%d",¦k);þcin¾>ë;
þprintf("Numberés:¥d\n",ë);þcout¼<¢Numberés:¢¼<ë;
þ}þ"}
þ
þWithÃ++,ùouãanïverloadôhe§>>'ánd§<<'ïperatorsándðrovide
þyourïwnòoutinesôoénputándïutputùourïwnïbjects.
þ
þRollùourïwnÉ/O ý%+6'ÿý¸íïstream02þRollùourïwnÉ/O

C++èasôwoãlasseséstreamándïstream÷hicháreõsedôoíakeénputánd
outputïbjectsærom.Ùouãanôhen÷riteùourïwnótreamïperatoræunctions:

ótructãlockû
þintèr,íin,óec;
þclock(intè,éntí,éntó)ûèr½è;íin½í;óec½ó; }
};
þýÚÿ
ÄýÂÿÄýÿýÂÿÄîoteïstreamïbjectsánd§<<'ïperator
þþ
þ
ïstream¦operator<<(ostream¦strm,ãlock¦c)
û
þstrm¼<ã.hr¼<¢:"¼<ã.min¼<¢:"¼<ã.sec;
}þ
þýÀÿÄãanãhainïperationsôogetherôoo
ãlockã(12,31,55);
ãout¼<ã;

Ðrintsïut:
±2:31:55þFeatureÍenuenuý
#.'2ÿýÏïôinline01þInlineÆunctions
þ
þTheseáreæunctionsôhat,óimilarôoíacros,áreénserted
þinline÷hereverãalled.Ôhisóavesôheïverheadïfáæunction
þcall.Âelowésánåxample:
þ
þ
inlineäoubleôaxem(doubleø)
þ
{
þ returnø*0.50;
þ
}
þ
þ
net½ôaxem(gross);þ Featurëý#eÍenu
þ
þIt'sásôhoughùouóaid
þ
þ
net½çrossª°.50;
þ
þNoteôhatõnlikeíacros,énlineæunctionsèaveåxactlyôhe
þsameóemanticsôhatòegularæunctionsäo.Énðarticular,
þtheyäon'tóufferæromôheótrangeócopingðroblemsùou
þcançet÷ithíacros,áý
) 4 '2ÿýÒñãvirt01
þVirtualÍethods
þ
þVirtualíethodsáreáópecialôypeïfíethod.Îo,ôheyáren't
þstoredénöirtualíemory,ïránythingìikeôhat.Állôhat
þhappensésôhat,õnlikeîormalíethods,ãallsôoöirtual
þmethodsáreâoundátòun-time,îotátãompile-time.Ôhis
þdynamicâindÿýÒòing,ïrìateâindingásét'sóometimesãalled,
þoccursâyõsingæunctionðointers.
þ
þEveryãlassïfïbject÷ithöirtualæunctionsèas÷hatésënown
þasáöirtualíethodôable.Énôhisôableáreðointersôoáll
þtheöirtualíethodsïfôheãlass.Åachïbjectïfôheãlass
þhasáðointerôoôØý%#hisôable,óo÷henáöirtualíethodés
þcalled,ôhisðointerésôraversed,ôheáppropriateôableåntry
þisïbtained,ándôhenôheæunctionðointerésôraversedôoôhe
þactualíethod.Ôhus,öirtualíethodsénvolveôwoìevels
þoféndirection. ý ‚%0a'ÿýÌô‚virt02

þSampleÃlass÷ithÖirtualÍethods
þ
þGivenôheãlassóhape÷ithôwoöirtualíethods,
þ
þclassóhapeû
þpublic:
þdoubleøo,ùo;
þshape(doubleø,äoubleù);¯/ãonstructorôoénitializeóhape
þvirtualäoubleárea(void);¯/æctnôoãomputeóurfaceárea
þvirtualäzýN#raw(void);þ//æctnôoärawóhape
þ};
þ
þtheîextãardóhowsèowôheöirtualíethodsôableìookæor
þanïbjectïfôhisãlass.
þ
þ ýƒ$/a'ÿýhö virt03þAÖirtualÍethodÔable
þ
þShapeÏbject'sþ VirtualÍethodþActual
þ DataþTableþ
Function
þ
þýÚÿ
Äý¿ ýÚÿÄ ýÚÿ Äý¿
þý³ øo,ùo ý³ ý³þý³¨*area)()„ÿÄ óhape::area()
þýÃÿ
Äý´ ý³þýÃÿ Äý´
þý³ öptr„ÿÄýÙþý³¨*draw)()„ÿÄ óhape::draw()ûýn#
þýÀÿ
ÄýÙþ ýÀÿ ÄýÙ
þ
þSoôoãalláóhapeïbjectsäraw()æunction,ãodeóomething
þsimilarôoôheæollowingésõsed:
þ
þ my_shape.draw() ÿÄ ª(my_shape.vptr[1]);
þ
þThatés,åachöirtualíethodéséndexedïutïfôheôable.Ôhis
þindexingésãomputedátãompileôime. ý„$/a'ÿý…øËvirt04

þ!So×hat?
þ
þByîow,ùou'reôhinking¢So÷hat?"×hat'sóoçreatáboutôhis
þelaborateæunctionðointerócheme?×ell,óuppose÷eõsed
þinheritanceándäerivedáîewãlassæromóhape:
þ
þclassãircleºðublicóhapeû
þpublic:
þdoubleòadius;
þcircle(doubleø,äoubÁý”#leù,äoubleò);
þdoubleárea(void);¯/ïverridesóhape::area()
þdraw(void);þ//ïverridesäraw::area()
þ};
þ
þTheîextãardóhowsèowôheöirtualíethodôable÷ouldìookîow:
þ
þ
Virtualíethodôableæorã ý
-…1<a'ÿýhú@virt05
þVirtualÍethodÔableæorÃircles
þ
þCircleÏbject'sþ VirtualÍethodþActual
þDataþTableþ
Function
þ
þýÚÿ
Äý¿ ýÚÿÄ ýÚÿ Äý¿
þý³ øo,ùo ý³ ý³þý³¨*area)()„ÿÄ ãircle::area()
þý³ òadius ý³ ý³þýÃÿ Äý´
þýÃÿ
Äý´ ý³þý³¨*draw)()„ÿÿýhûÄ ãircle::draw();
þý³ öptr„ÿÄýÙþýÀÿ ÄýÙ
þýÀÿ
ÄýÙ
þ
þTheãircleãlassèasáãopyïfôheöirtualíethodôableærom
þclassóhape,ándåachöirtualæunctionïverriddenâyôheãircle
þclass¨inôhisãaseállïfôhem)ãauseôheãorrespondingåntries
þinôheôableôoâeíodifiedôo7ý¶#ðointôoôheãircle'söersionïf
þtheæunctions.
þ
þS ý$†)4a'ÿýÁüévirt06þAÒeasonæorÔhisÍadness
þ
þThereòeallyésáòeasonæorôhisíadness.Étállowsõsôoõseá
þpointerôoánïbject,òatherôhanôheïbjectétself,ándótillâe
þguaranteedôhatôheòightöirtualíethod÷illâeãalled,âecause
þaðointerôoétésótored÷ithôheïbject.ÆoråxamplÿýÁýe:
þ
þshapeªp;þ //äeclareçenericóhapeðointer
þshapeó(0,0);þ//ándáçenericóhape
þcircleã(10,10,50);¯/ándáãircleóhape
þ
þp½¦s;þ //ðointôoóhape
þp->draw();þ//ãausesóhape::area()ôoâeãalled
þp½¦c;þ //ðointôoãircleÍoreáboutôhis®..
þp->draw();þ//àýÝ#ãausesóhape::circle()ôoâeãalled
þ
þThus,÷ithöirtualíethods,÷eãanèaveïuróhapeðointerðerform
þdifferentâehaviors,äependingïn÷hatëindïfóhapeétðoints
þto.Ôhisés÷hatðolymorphismésállábout!
þ
þOkay,Ïkay,Éâelieveùou,âutè ý,
>
ˆD‡'ÿýÃÿvirt07þDeclaringÖirtualÍethods
þ
þActually,ùou'veálreadyóeenèowôoäoôhis,âut,èereés
þtheóhapeãlasságain:
þ
þclassóhapeû
þpublic:
þdoubleøo,ùo;
þshape(doubleø,äoubleù);¯/ãonstructorôoénitializeóhape
þvirtualäoubleárea(void);¯/æctnôoãomputeÿýÃóurfaceárea
þvirtualäraw(void);þ//æctnôoärawóhape
þ}; ž
þ ýÀÿÄÖirtualëeyword
þ
þVirtualæunctionsáreäeclaredõsingôheöirtualëeyword.Îote
þthatôhisíustâeäoneénôheâaseãlass,¨likeóhapeèere),âut
þitäoesn'tèaveôoâeenénôheäerivedãlasses.Ïnceöirtual,
ý$þalwaysöirtua ý%a*,'ÿýø oneway01

þAÏne×ayÔypeÃastingÁvenue
þ
þYouíightèaveîoticedénïneïfôheãards¨Thisïne®..)
þthatáâaseãlassðointer,óuchásóhapeªp,ãanðointîotïnly
þtoáóhapeïbject,âutálsoôoáãircleïbject.Ôhisésäone
þWITHOUTÔYPEÃASTING.Áctually,ùouãanðointáâaseãlassðoÿýøinter
þtoányäerivedãlassïbject.Æorénstance,óhapeªpãouldðointôo
þrect,ïrâox3d,ïrãylinder,ándïnándïn.Ôhus,ôhere'sáìot
þofðowerðackedénôhatðointer.
þ
þHowever,ôheãonverseésîotôrue.Æorénstance,áãircleðointer
þcannotðointôoáçenericóhapeïbject.×hy?Âe˜ý($causeãircles
þhaveáòadius,óhapesäon't.Ôhuséfùouôriedôoíakeáóhape
þactìikeáãircle,ándáccessét'sòadius,ôhings÷ouldòeally
þgetæouledõp!
þ
þBackôo ý0;†5†'ÿý²Dfriend01
þFriendsïfÃlasses
þ
þClassesãanèaveæriends.Ôheseáreæunctionsôhat,álthough
þtheyáreîotðartïfáãlass,ãanèaveáccessôoôheðrivate
þpartsïfôheãlass¨noäirtyíindsèereðlease!).Æorénstance,
þtakeïurôeller_machineãlass,÷ithðrivateíemberâig_buckÿý²s.
þWeãanáddá¢friendly"ÉRSôaxæunctionôoét:
þ
þ classôeller_machineû
þ private:þ//ðrivateëeyword
þ doubleâig_bucks;þ
//ðrivateíember
þ public:þ//ótartsðublicóection
þ voidäeposit(doubleámt); ¯/ðublicíember
þ double÷ithdraw(void);þ//ðublicíember
þLýN$ friendöoidérs(void);þ//¢friendly"æunction
þ };
þ
þMore®.. ÄataÈidin*ýŠ)9,3&ÿý*lfriend02


þAÆriendlyÉRSæunction
þ
þ
þ voidérs(void)
þ {
þ big_bucks­=âig_bucksª°.10;¯/ôake±0%ïffôheôop
þ }
þ
þNoteôhatálthough÷eäeclaredérs()énsideôheãlass,étés
þnotáãlassíethod!Ôhisésäueôoôheæriendëeywordôhat
þwasõsed.Âutåvenôhoughét'sîotjýd$áíethod,étãanótillòake
þoff±0%ïfïuróavingsæromïurèiddenâig_bucksótorage.
þ(Someæriend!)
þ
þDataÈi ý"9(/&-ÿý¶„@G)ÑKè³KÔlKµÐK J KW :
K[
K*ÔKëK$uKŒ³KÊ#K0\KixK5!KL!‹#K¢#I$Kt$þ%Ko&Ä'K+(‡*ÿý¶ KÆ*¥,Kø,°.KÑ. 1KA1•3KÞ3Ö5K÷5A8Kb8Î9Kï9Ù:K;=K%=n>K>ž@KÓ@BKAB.DKcD+EK`EÜFKýFFHKqHŸIKÊI€KK¡KMKKMâNKOGPÿý¶
KrPìQKRˆSK©SåUKVùWK.X¡YKÂY¸[KÙ[Ù]Kú]{_Kœ_UaKŠaDdKed¡fKÂfhK #½Ê¾KᾝÁK´ÁÃÃKÚÃÄÆKÛÆóÈK
ÉCËKZËøÍKÎ
ÐK+ÐXÒKyҟÔKÀÔÚÖKûÖÙKIÙÛKÛºÜKÑÜÃÝKÚÝÖßK÷ßoáKáœãK³ã?åKVåÂæKÙæ¤èK´ýÅèwêK¢ê—ìK¸ì¸îKÏî»ðKÒð«óKÌóGõKhõd÷K…÷GùKhù ûKÁû¢þKÃþ×Kø‘K²ÿK*•KGÿýkp 
 +3:>HLTX]bglqx~ƒŠ“¤­ ² ¸ ¾ Ã È Ô Û
ß
åíõùý#,6?DLT[dkpw~ƒ”ž#ª#ÿýk·#Ä#Ï(Û(æ(ñ(ù--033!3)3.545<7F7Q9X9f:m;u<>‹>™>£?¨?±?¸?¾?Æ?ÌAÔEÞEêEïHõKüNR
RUUU$U+U4U7ZD^P^Y`b`laqayb€eˆff˜fœg§g«g²g»ˆýgÉgÒgÞjãlêpówýwzzz#{-{9{D|H|O|V|a~h~l€s{ƒ†‰ˆˆ‘ˆ–ˆžˆ£ˆ«‰²‰exteÿýôºhomestart?helpcommandskeyskeystrokeshotkeyshotkeykeykeystrokehotcommandbarmenusrchprevnextquitswitchfilesfilechangechangingswitchingsearchkeywordseditfieldbooksbookinfoinformationprimerwhoabouthistoryoriginsc++ÿýôoopextensionextensionsfeaturefeaturesfunctionfunctionsnicetiesniceexpressobjectsobjectbuildingblocksmakemakingcookiedatavariablesaccessaccessingconstructorconstructorsinitializinginitializedestructorsdestructordestroyingcÿýôleanupmethodsmethodscopingmessagemessagestalkingtalkclassclassesstructurestructureshidingencapsulationpublicprivateprotectedinheritanceextensibilityextendingbasesubclassparentchildderivedsupersharinghierarchyhierarchiestrÿýôeeshapecirclecylinderrectrectangleboxboxesbox3d3d-box3d-boxes3dpolymorphismoverloadingoverloadoperatoroperatorsbindbindingstaticdynamicbridgebridginggapdecompressrunlengthencodingdecompressioncompresscompressionoopyfilÞýterfrontierreferencereferencesdefaultargumentargumentsprototypeprototypingprototypesnewdeletememoryallocationstreamI/OinlinevirtualtablemadnessonewaytypecastingcastpointerfriendfriendsethodýPressÒeturn®.. Hypeý

þ

þNoþYes'no': ý
þ
þÁboutôheÁuthoruthorýótartôheÃ++Ôutorial  Usýenåditing
þstrings.on thýôheãommand.r theýâyðressingôheÅSCëey.file &ýy
þtoñuitôheóearchóession. indiýrtôheådit.
þ-More®.. fielýmandÂar®..n
conýckel"C++ ýnalçuideôoÃ++!xplan*ýeachèimïnÃompuServeÛ73057,³172]dale,)ýîow?
þ
þTakeôheÐlungeéntoÃ++see wýksátÃ++åxtensions÷÷÷÷÷ ý.in()
ýnu®.. O ý
þOtherÎicetiesbject ý++ÆeatureÐackÔrain®..featuýuâackèere. of y ýisénãaseùouçetìost
þ ýMore®..þOOE ³-ý³þTheÉngredients®.. ÏOE
þýÀÿÄýÙithdrýingÂlocksþOOEng meýns®..þ OOEÍÍÍÍÍýts ÏOE
þ ³ýbjectsþ OOElatesýourÇuideþOOEbroke+ýAccessingÄata®..
þýÀÿÄýÙ
þ,OOE-----ýta®..þOOEe my_ýteíembersþ
OOEnal. ýnow
þ
þ
þ"OOE shýÔourÇuide ÏOE caýþ
þTourÇuideþOOE ýorsþOOEble wýénlineþOOEler_mýOOEid);
ýtorsãalled ÏOE ýrÇuideþOOEc memýrsþOOEt(douýénlineþOOE ~telýOOE ý®..þOOE reac
ýrnate m+ýsþý³
þ ýÀÿÄýÙ
þ1TourÇuide ÏOEÄijÄ<ýhis÷ork?þOOE
ý÷ork?þOOEcks <ýethods®..þOOEou'reýngíethods®..þOOE¿
toýeþOOE mýeÍessage®..þOOE ýTourÇuide ÏOE ýass
þ
þ#OOE
þ tempýresþOOEarea()ý.
þComponentsïfáãlass®..þOOE haveýnuþOOE
þ doubýmpleþClassíenuþOOEof clýíenuþOOEPrivaýenuþOOE Clýþ

þClassíenuþOOEe on ý Ãlassíenu ÏOEs wheýrachies
ýhildãlass BaseýnuþOOEnheriýritanceÍenuþOOE
þthods+ýMore®..þInheritanceíenuþOOE
þ
ýers.
þ
þ Back®..d to
ýal daýnuþOOE ÚÄÄýritanceíenuþOOE is,
ýnuþOOE
þ ÚÄÄýÈierarchyþOOE to cýOOEs ýpeÈierarchyþOOEarchyýerarchyþOOEshapeýeÈierarchyþOOEcirclýierarchyþOOEOOE
ýpeÈierarchyþOOEal voýrarchyþOOE the ýeÈierarchyþOOEt;
ýeÈierarchyþOOEþretýeÈierarchyþOOE shapýpeÈierarchyþOOEt sizýerarchyþOOEoóetýpeÈierarchyþOOE addiýrarchyþOOE ýeÈierarchyþOOEdepthýÈierarchyþOOE ý.
þ{
þ
radius½ò;
þ} ýritanceÍenuþOOE ýceÍenu ÏOE³ ýþOOElity
ýlymorphismÍenuþOOEt kno#ýolymorphismþFeatureíenu haviýFeatureÍenu} ýonôoõse.al + ýynamicÂinding
þ ýindingÍenu;
ý. ÂindingÍenu ýÍenuval +ý..þBindingÍenuthe cýogram.
þ
þ Let'sÇoct-Or#ýy.
þ
þFirst÷ithî..
þecompýng÷ithôhis?t--) #ýittleíoreïbject-orientedquiteý...
þ}
þ Then®.. (ýDecompressing­-ÆilterÓtyle®.. leng ý.)++; 'ýeédea.
þ
þMoreáboutôhis®..ne, o ýButét'såasierénÃ++®..) putýôheÃ++Ærontier®..

Tha!ýmpressorÃonstructor®..s tak)ý)æunction.
þTheîext()æunctionh theýôheíainðrograménÃ++ at? "ý!
þ
þAltogetherîow®..C pro+ýt½°;
þ 014: }
þ
þLines±5-27®..; src'ý
þ027: }
þ
þLines²8-36®..haracýþ
þBackôoÓtart®.. ý®..þFeatureÍenu 42; ýÍenu' !

ýeatureÍenu // o ýard.
þ
þFeatureÍenuf theýî..þFeatureÍenu it
kýeatureÍenu autoý®..þFeatureÍenu cin ýndôheyáreôypeãhecked! stra(ý
þ
þExample®..þBindingÍenuhe
acýNext®..þBindingÍenu obje%ý
þ
þSo×hat?þBindingÍenuape.v!ýircles®.. ÂindingÍenuld lo&ýo÷hatágain?®..þBindingÍenue the&ýowäoÉäeclareöirtualíethods?avior#ýl.
þ
þBindingÍenuþOOEthe d%ýöirtualíethodäiscussion®..a cirýg Æeaturesmber
ýdingþFeatures big_ ýA HyperGuide to C++

  3 Responses to “Category : C Source Code
Archive   : CPPTOUR.ZIP
Filename : CPPTOUR.HTX

  1. Very nice! Thank you for this wonderful archive. I wonder why I found it only now. Long live the BBS file archives!

  2. This is so awesome! 😀 I’d be cool if you could download an entire archive of this at once, though.

  3. But one thing that puzzles me is the “mtswslnkmcjklsdlsbdmMICROSOFT” string. There is an article about it here. It is definitely worth a read: http://www.os2museum.com/wp/mtswslnk/