c++ programming in easy steps, 5th edition

357

Upload: others

Post on 05-Oct-2021

8 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: C++ Programming in easy steps, 5th Edition
Page 2: C++ Programming in easy steps, 5th Edition

MikeMcGrath

C++Programming

FifthEdition

Page 3: C++ Programming in easy steps, 5th Edition

IneasystepsisanimprintofInEasyStepsLimited16HamiltonTerrace.HollyWalk.LeamingtonSpaWarwickshire.CV324LYwww.ineasysteps.com

FifthEdition

Copyright© 2017byInEasyStepsLimited.Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutpriorwrittenpermissionfromthepublisher.

NoticeofLiabilityEveryefforthasbeenmadetoensurethatthisbookcontainsaccurateandcurrentinformation.However,InEasyStepsLimitedandtheauthorshallnotbeliableforanylossordamagesufferedbyreadersasaresultofanyinformationcontainedherein.

TrademarksAlltrademarksareacknowledgedasbelongingtotheirrespectivecompanies.

Page 4: C++ Programming in easy steps, 5th Edition

Contents

1GettingstartedIntroducingC++InstallingacompilerWritingyourfirstprogramCompiling&runningprogramsCreatingvariablesEmployingvariablearraysEmployingvectorarraysDeclaringconstantsSummary

2PerformingoperationsDoingarithmeticAssigningvaluesComparingvaluesAssessinglogicExaminingconditionsEstablishingsizeSettingprecedenceCastingdatatypesSummary

3MakingstatementsBranchingwithifSwitchingbranchesLoopingforLoopingwhileDeclaringfunctionsPassingargumentsOverloadingfunctionsOptimizingfunctionsSummary

4HandlingstringsCreatingstringvariablesGettingstringinputSolvingthestringproblemDiscoveringstringfeaturesJoining&comparingstringsCopying&swappingstringsFindingsubstringsReplacingsubstringsSummary

Page 5: C++ Programming in easy steps, 5th Edition

5ReadingandwritingfilesWritingafileAppendingtoafileReadingcharacters&linesFormattingwithgetlineManipulatinginput&outputPredictingproblemsRecognizingexceptionsHandlingerrorsSummary

6PointingtodataUnderstandingdatastorageGettingvalueswithpointersDoingpointerarithmeticPassingpointerstofunctionsMakingarraysofpointersReferencingdataPassingreferencestofunctionsComparingpointers&referencesSummary

7CreatingclassesandobjectsEncapsulatingdataCreatinganobjectCreatingmultipleobjectsInitializingclassmembersOverloadingmethodsInheritingclasspropertiesCallingbaseconstructorsOverridingbasemethodsSummary

8HarnessingpolymorphismPointingtoclassesCallingavirtualmethodDirectingmethodcallsProvidingcapabilityclassesMakingabstractdatatypesBuildingcomplexhierarchiesIsolatingclassstructuresEmployingisolatedclassesSummary

9ProcessingmacrosExploringcompilationDefiningsubstitutesDefiningconditionsProvidingalternativesGuardinginclusions

Page 6: C++ Programming in easy steps, 5th Edition

UsingmacrofunctionsBuildingstringsDebuggingassertionsSummary

10ProgrammingvisuallyStartingaUniversalprojectInsertingpagecomponentsImportingprogramassetsDesigningthelayoutAddingruntimefunctionTestingtheprogramAdjustingtheinterfaceDeployingtheapplicationSummary

Page 7: C++ Programming in easy steps, 5th Edition

PrefaceThecreationofthisbookhasprovidedme,MikeMcGrath,awelcomeopportunitytoupdatemypreviousbooksonC++programmingwiththelatesttechniques.AllexamplesIhavegiveninthisbookdemonstrateC++featuressupportedbycurrentcompilersonbothWindowsandLinuxoperatingsystems,andintheMicrosoftVisualStudiodevelopmentsuite,andthebook’sscreenshotsillustratetheactualresultsproducedbycompilingandexecutingthelistedcode.

Conventionsinthisbook

Inordertoclarifythecodelistedinthestepsgivenineachexample,Ihaveadoptedcertaincolorizationconventions.ComponentsoftheC++languageitselfarecoloredblue,numericandstringvaluesarered,programmer-specifiednamesareblack,andcommentsaregreen,likethis:

//Storethenoutput atext st ringvalue.st ringmyMessage=“HellofromC++!”;cout <<myMessage;

Additionally,inordertoidentifyeachsourcecodefiledescribedinthesteps,acolorediconandfilenameappearsinthemarginalongsidethesteps:

main.cpp

header.h

Grabbingthesourcecode

ForconvenienceIhaveplacedsourcecodefilesfromtheexamplesfeaturedinthisbookintoasingleZIParchive,providingversionsforWindowsandLinuxplatformsplustheMicrosoftVisualStudioIDE.Youcanobtainthecompletearchivebyfollowingtheseeasysteps:

Browsetowww.ineasysteps.comthennavigatetoFreeResourcesandchoosetheDownloadssection

FindC++Programmingineasysteps,5thEditioninthelistthenclickonthehyperlink

Page 8: C++ Programming in easy steps, 5th Edition

entitledAllCodeExamplestodownloadthearchive

Now,extractthearchivecontentstoanyconvenientlocationonyourcomputer

Isincerelyhopeyouenjoydiscoveringthepowerful,expressivepossibilitiesofC++ProgrammingandhaveasmuchfunwithitasIdidinwritingthisbook.

Page 9: C++ Programming in easy steps, 5th Edition

1

Gettingstarted

WelcometotheexcitingworldofC++programming.ThischapterdemonstrateshowtocreateasimpleC++programand

howtostoredatawithinaprogram.

IntroducingC++InstallingacompilerWritingyourfirstprogramCompiling&runningprogramsCreatingvariablesEmployingvariablearraysEmployingvectorarraysDeclaringconstantsSummary

Page 10: C++ Programming in easy steps, 5th Edition
Page 11: C++ Programming in easy steps, 5th Edition

IntroducingC++C++isanextensionoftheCprogramminglanguagethatwasfirstimplementedontheUNIXoperatingsystembyDennisRitchiewaybackin1972.Cisaflexibleprogramminglanguagethatremainspopulartoday,andisusedonalargenumberofplatformsforeverythingfrommicrocontrollerstothemostadvancedscientificsystems.

Apowerfulprogramminglanguage(pronounced“seeplusplus”),designedtoletyouexpressideas.

C++wasdevelopedbyDr.BjarneStroustrupbetween1983-1985whileworkingatAT&TBellLabsinNewJersey.HeaddedfeaturestotheoriginalClanguagetoproducewhathecalled“Cwithclasses”.TheseclassesdefineprogrammingobjectswithspecificfeaturesthattransformtheproceduralnatureofCintotheobject-orientedprogramminglanguageofC++.

TheCprogramminglanguagewassonamedasitsucceededanearlierprogramminglanguagenamed“B”thathadbeenintroducedaround1970.Thename“C++”displayssomeprogrammers’humorbecausetheprogramming++incrementoperatordenotesthatC++isanextensionoftheClanguage.

C++,likeC,isnotplatform-dependent,soprogramscanbecreatedonanyoperatingsystem.MostillustrationsinthisbookdepictoutputontheWindowsoperatingsystempurelybecauseitisthemostwidelyuseddesktopplatform.TheexamplescanalsobecreatedonotherplatformssuchasLinuxormacOS.

WhylearnC++programming?TheC++languageisfavoredbymanyprofessionalprogrammersbecauseitallowsthemtocreatefast,compactprogramsthatarerobustandportable.

UsingamodernC++IntegratedDevelopmentEnvironment(IDE),suchasMicrosoft’sVisualStudioCommunityEdition,theprogrammercanquicklycreatecomplexapplications.Buttousethesetoolstogreatesteffect,theprogrammermustfirstlearnquiteabitabouttheC++languageitself.

ThisbookisanintroductiontoprogrammingwithC++,givingexamplesofprogramcodeanditsoutputtodemonstratethebasicsofthispowerfullanguage.

Page 12: C++ Programming in easy steps, 5th Edition

Microsoft’sfreeVisualStudioCommunityEditionIDEisusedinthisbooktodemonstratevisualprogramming.

ShouldIlearnCfirst?OpinionisdividedonthequestionofwhetheritisanadvantagetobefamiliarwithCprogrammingbeforemovingontoC++.Itwouldseemlogicaltolearntheoriginallanguagefirstinordertounderstandthelargerextendedlanguagemorereadily.However,C++isnotsimplyalargerversionofC,astheapproachtoobject-orientedprogrammingwithC++ismarkedlydifferenttotheproceduralnatureofC.Itis,therefore,arguablybettertolearnC++withoutpreviousknowledgeofCtoavoidconfusion.

Thisbookmakesnoassumptionthatthereaderhaspreviousknowledgeofanyprogramminglanguage,soitissuitableforthebeginnertoprogramminginC++,whethertheyknowCornot.

IfyoudofeelthatyouwouldbenefitfromlearningtoprograminC,beforemovingontoC++,werecommendyoutrytheexamplesinCProgrammingineasystepsbeforereadingthisbook.

StandardizationofC++AstheC++programminglanguagegainedinpopularity,itwasadoptedbymanyprogrammersaroundtheworldastheirprogramminglanguageofchoice.Someoftheseprogrammersbegantoaddtheirownextensionstothelanguage,soitbecamenecessarytoagreeuponapreciseversionofC++thatcouldbecommonlysharedinternationallybyallprogrammers.

AstandardversionofC++wasdefinedbyajointcommitteeoftheAmericanNationalStandardsInstitute(ANSI)andtheIndustryOrganizationforStandardization(ISO).ThisversionissometimesknownasANSIC++,andisportabletoanyplatformandtoanydevelopmentenvironment.

TheexamplesgiveninthisbookconformtoANSIC++.Exampleprogramsruninaconsolewindow,suchastheCommandPromptwindowonWindowssystemsorashellterminalwindowonLinuxsystems,todemonstratethemechanicsoftheC++languageitself.AnexampleinthefinalchapterillustrateshowcodegeneratedautomaticallybyavisualdevelopmenttoolontheWindowsplatformcan,onceyou’refamiliarwiththeC++language,beeditedtocreateagraphical,windowedapplication.

Page 13: C++ Programming in easy steps, 5th Edition

“ISO”isnotanacronymbutisderivedfromtheGreekword“isos”meaning“equal”–asin“isometric”.

Page 14: C++ Programming in easy steps, 5th Edition
Page 15: C++ Programming in easy steps, 5th Edition

InstallingacompilerC++programsareinitiallycreatedasplaintextfiles,savedwiththefileextensionof“.cpp”.Thesecanbewritteninanytexteditor,suchasWindows’NotepadapplicationortheVieditoronLinux.

InordertoexecuteaC++program,itmustfirstbe“compiled”intobytecodethatcanbeunderstoodbythecomputer.AC++compilerreadsthetextversionoftheprogramandtranslatesitintoasecondfile–inmachine-readable,executableformat.

Shouldthetextprogramcontainanysyntaxerrors,thesewillbereportedbythecompilerandtheexecutablefilewillnotbebuilt.

IfyouareusingtheWindowsplatformandhaveaC++IntegratedDevelopmentEnvironment(IDE)installed,thenyouwillalreadyhaveaC++compileravailable,asthecompilerisanintegralpartofthevisualIDE.Theexcellent,freeMicrosoftVisualC++ExpressIDEprovidesaneditorwindow,wheretheprogramcodecanbewritten,andbuttonstocompileandexecutetheprogram.VisualIDEscan,however,seemunwieldywhenstartingoutwithC++becausetheyalwayscreatealargenumberof“project”filesthatareusedbyadvancedprograms.

ThepopularGNUC++CompilerisavailablefreeunderthetermsoftheGeneralPublicLicense(GPL).ItisincludedwithmostdistributionsoftheLinuxoperatingsystem.TheGNUC++CompilerisalsoavailableforWindowsplatformsandisusedtocompileexamplesthroughoutthisbook.

TodiscoverifyoualreadyhavetheGNUC++Compileronyoursystem,typec++-vatacommandpromptthenhitReturn.Ifit’savailable,thecompilerwillrespondwithversioninformation.IfyouareusingtheLinuxplatformandtheGNUC++Compilerisnotavailableonyourcomputer,installitfromthedistributiondisc,downloaditfromtheGNUwebsite,oraskyoursystemadministratortoinstallit.

TheGNU(pronounced“guh-new”)Projectwaslaunchedbackin1984todevelopacompletefreeUnix-likeoperatingsystem.PartofGNUis“MinimalistGNUforWindows”(MinGW).MinGWincludestheGNUC++CompilerthatcanbeusedonWindowssystemstocreateexecutableC++programs.WindowsuserscandownloadandinstalltheGNUC++Compilerbyfollowingtheinstructionsbelow.

Page 16: C++ Programming in easy steps, 5th Edition

ThetermsandconditionsoftheGeneralPublicLicensecanbefoundonlineatgnu.org/copyleft/gpl.html

Withaninternetconnectionopen,launchawebbrowserthennavigatetosourceforge.net/projects/mingwandclicktheDownloadbuttontogettheMinGWinstaller

LaunchtheinstallerandacceptthesuggestedlocationofC:\MinGWinthe“InstallationManager”dialog

ChoosethebaseandC++compileritems,thenclickInstallation,ApplyChangestocompletetheinstallation

TheMinGWinstallationprocessmaybesubjecttochange,butcurrentguidancecanbefoundatmingw.org/wiki/Getting_Started

TheMinGWC++CompilerisabinaryexecutablefilelocatedatC:\MinGW\bin.Toallowittobeaccessiblefromanysystemlocation,thisfoldershouldnowbeaddedtotheSystemPath:

InWindows’ControlPanel,clicktheSystemiconthenselecttheAdvancedSystemSettingsitemtolaunchthe“SystemProperties”dialog

IntheSystemPropertiesdialog,clicktheEnvironmentVariablesbutton,selectthePathsystemvariable,thenclicktheEditbuttonandaddthelocationC:\MinGW\bin;

ClickOKtocloseeachdialog,thenopenaCommandPromptwindowandenterthecommandc++.Iftheinstallationissuccessful,thecompilershouldrespondthatyouhavenotspecifiedanyinputfilesforcompilation:

Page 17: C++ Programming in easy steps, 5th Edition

LocationaddressesinthePathstatementmustendwitha;semi-colon.

Page 18: C++ Programming in easy steps, 5th Edition
Page 19: C++ Programming in easy steps, 5th Edition

WritingyourfirstprogramFollowthesesteps,copyingthecodeexactlyasitislisted,tocreateasimpleC++programthatwilloutputthetraditionalfirstprogramgreeting:

hello.cpp

Openaplaintexteditor,suchasWindows’Notepad,thentypethese“preprocessordirectives”#include<iost ream>usingnamespacestd;

Afewlinesbelowthepreprocessordirectives,adda“comment”describingtheprogram//AC++Programtooutput agreet ing.

Belowthecomment,adda“mainfunction”declarationtocontaintheprogramstatementsint main(){

}

Betweenthecurlybrackets(braces)ofthemainfunction,insertthisoutput“statement”cout <<“HelloWorld!”<<endl;

Next,insertafinal“return”statementinthemainfunctionreturn0;

Savetheprogramtoanyconvenientlocationas“hello.cpp”–thecompleteprogramshouldlooklikethis:

Page 20: C++ Programming in easy steps, 5th Edition

Commentsthroughoutthisbookareshowningreen–todifferentiatethemfromothercode.

Aftertypingthefinalclosing}braceofthemainmethod,alwayshitReturntoaddanewlinecharacter–yourcompilermayinsistthatasourcefileshouldendwithanewlinecharacter.

Theseparatepartsoftheprogramcodeherecanbeexaminedindividuallytounderstandeachpartmoreclearly:

• PreprocessorDirectives–theseareprocessedbythecompilerbeforetheprogramcode,somustalwaysappearatthestartofthepage.Here,the#includeinstructsthecompilertousethestandardC++input/outputlibrarynamediost ream,specifyingthelibrarynamebetween<>angledbrackets.Thenextlineisthe“usingdirective”thatallowsfunctionsinthespecifiednamespacetobeusedwithouttheirnamespaceprefix.Functionsoftheiost reamlibraryarewithinthestdnamespace–sothisusingdirectiveallowsfunctionssuchasstd::cout andstd::endltobesimplywrittenascout andendl.

• Comments–theseshouldbeusedtomakethecodemoreeasilyunderstoodbyothers,andbyyourselfwhenrevisitingthecodelater.InC++programming,everythingonasinglelineaftera//double-slashisignoredbythecompiler.

• Mainfunction–thisisthemandatoryentrypointofeveryC++program.Programsmaycontainmanyfunctions,buttheymustalwayscontainonenamedmain,otherwisethecompilerwillnotcompiletheprogram.Optionally,theparenthesesafterthefunctionnamemayspecifyacomma-separatedlistof“argument”valuestobeusedbythatfunction.Followingexecution,thefunctionmustreturnavaluetotheoperatingsystemofthedatatypespecifiedinitsdeclaration–inthiscase,anint (integer)value.

• Statements–thesearetheactionsthattheprogramwillexecutewhenitruns.Eachstatementmustbeterminatedbyasemi-colon,inthesamewaythatEnglishlanguagesentencesmustbeterminatedbyaperiod(fullstop).Here,thefirststatementcallsuponthecout libraryfunctiontooutputtextandanendlcarriagereturn.Thesearedirectedtostandardoutputbythe<<outputstreamoperator.NoticethattextstringsinC++mustalwaysbeenclosedwithindoublequotes.ThefinalstatementemploystheC++returnkeywordtoreturnazerointegervaluetotheoperatingsystem–asrequiredbythemainfunctiondeclaration.Traditionally,returningazerovalueindicatesthattheprogram

Page 21: C++ Programming in easy steps, 5th Edition

executedsuccessfully.

TheC++compileralsosupportsmultiple-lineC-stylecommentsbetween/*and*/–buttheseshouldonlyeverbeusedinC++programmingto“comment-out”sectionsofcodewhendebugging.

Noticehowtheprogramcodeisformattedusingspacingandindentation(collectivelyknownaswhitespace)toimprovereadability.AllwhitespaceisignoredbytheC++compiler.

Page 22: C++ Programming in easy steps, 5th Edition
Page 23: C++ Programming in easy steps, 5th Edition

Compiling&runningprogramsTheC++sourcecodefilesfortheexamplesinthisbookarestoredinadirectorycreatedexpresslyforthatpurpose.Thedirectoryisnamed“MyPrograms”–itsabsoluteaddressonaWindowssystemisC:\MyProgramsandonLinuxit’s/home/user/MyPrograms.Youcanrecreatethisdirectorytostoreprogramsawaitingcompilation:

Movethe“hello.cpp”programsourcecodefile,createdhere,tothe“MyPrograms”directoryonyoursystem

Atacommandprompt,usethe“cd”commandtonavigatetothe“MyPrograms”directory

Enteracommandtoattempttocompiletheprogramc++hello.cpp

Youcanseethecompilerversionnumberwiththecommandc++--versionanddisplayallitsoptionswithc++--help.

Whentheattemptsucceeds,thecompilercreatesanexecutablefilealongsidetheoriginalsourcecodefile.Bydefault,theexecutablefileisnameda.exeonWindowssystemsanda.outonLinux.Compilingadifferentsourcecodefileinthesamedirectorywouldnowoverwritethefirstexecutablefilewithoutwarning.Thisisobviouslyundesirable,soacustomnamefortheexecutablefileshouldbespecifiedwhencompilingprograms,usingthecompiler ’s-ooptioninthecompilecommand.

Thecommandc++isanaliasfortheGNUC++Compiler–thecommandg++canalsobeused.

Enteracommandtocompiletheprogram,creatinganexecutablefilenamed“hello.exe”alongsidethesourcefilec++hello.cpp-ohello.exe

Page 24: C++ Programming in easy steps, 5th Edition

TorunthegeneratedexecutableprogramfileinWindows,simplyenterthefilenameatthepromptinthe“MyPrograms”directory–optionally,thefileextensionmaybeomitted.InLinux,thefullfilenamemustbeused,precededbya./dot-slash–asLinuxdoesnotlookinthecurrentdirectoryunlessitisexplicitlydirectedtodoso:

Page 25: C++ Programming in easy steps, 5th Edition

AllcommandlineexamplesinthisbookhavebeencompiledandtestedwiththelatestGNUC++Compileravailableatthetimeofwriting–theymaynotreplicateexactlywithothercompilers.

Page 26: C++ Programming in easy steps, 5th Edition
Page 27: C++ Programming in easy steps, 5th Edition

CreatingvariablesA“variable”islikeacontainerinaC++programinwhichadatavaluecanbestoredinsidethecomputer ’smemory.Thestoredvaluecanbereferencedusingthevariable’sname.

Theprogrammercanchooseanynameforavariable,providingitadherestotheC++namingconventions–achosennamemayonlycontainletters,digits,andtheunderscorecharacter,butcannotbeginwithadigit.Also,theC++keywords,listedontheinsidecoverofthisbookmustbeavoided.It’sgoodpracticetochoosemeaningfulnamestomakethecodemorecomprehensible.

Tocreateanewvariableinaprogramitmustbe“declared”,specifyingthetypeofdataitmaycontainanditschosenname.Avariabledeclarationhasthissyntax:

data-typevariable-name;

Namesarecase-sensitiveinC++–sovariablesnamedVAR,Var,andvararetreatedasthreeindividualvariables.Traditionally,C++variablenamesarelowercaseandseldombeginwithanunderscore,assomeC++librariesusethatconvention.

Multiplevariablesofthesamedatatypecanbecreatedinasingledeclarationasacomma-separatedlistwiththissyntax:

data-typevariable-name1,variable-name2,variable-name3;

ThefivebasicC++datatypesarelistedinthetablebelow,togetherwithabriefdescriptionandexamplecontent:

DataType: Descript ion: Example:

char Asinglebyte,capableofholdingonecharacter ‘A’

int Anintegerwholenumber 100

Page 28: C++ Programming in easy steps, 5th Edition

float Afloating-pointnumber,correcttosixdecimalplaces 0.123456

double Afloating-pointnumber,correctto10decimalplaces 0.0123456789

bool ABooleanvalueoft rueorfalse,ornumericallyzeroisfalseandanynon-zeroistrue

falseor0t rueor1

Charactervaluesofthechardatatypemustalwaysbeenclosedbetweensinglequotes–notdoublequotes.

Variabledeclarationsmustappearbeforeexecutablestatements–sotheywillbeavailableforreferencewithinstatements.

Whenavalueisassignedtoavariableitissaidtohavebeen“initialized”.Optionally,avariablemaybeinitializedinitsdeclaration.Thevaluestoredinanyinitializedvariablecanbedisplayedonstandardoutputbythecout function,whichwasusedheretodisplaythe“HelloWorld!”greeting.

vars.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertstatementstodeclareandinitializevariablesofvariousdatatypescharlet ter;let ter=‘A’;//Declaredtheninit ialized.int number;number=100;//Declaredtheninit ialized.float decimal=7.5;//Declaredandinit ialized.doublepi=3.14159;//Declaredandinit ialized.boolisTrue=false;//Declaredandinit ialized.

Now,insertstatementstooutputeachstoredvaluecout <<“charlet ter:”<<let ter<<endl;

Page 29: C++ Programming in easy steps, 5th Edition

cout <<“int number:”<<number<<endl;cout <<“float decimal:”<<decimal<<endl;cout <<“doublepi:”<<pi<<endl;cout <<“boolisTrue:”<<isTrue<<endl;

Save,compile,andruntheprogramtoseetheoutput

AlwaysbeginBooleanvariablenameswith“is”sotheyareinstantlyrecognizableasBooleans.Also,use“lowerCamelCase”forallvariablenamesthatcomprisemultiplewords–whereallexceptthefirstwordbeginwithuppercase,like“isTrue”.

Page 30: C++ Programming in easy steps, 5th Edition
Page 31: C++ Programming in easy steps, 5th Edition

EmployingvariablearraysAnarrayisavariablethatcanstoremultipleitemsofdata–unlikearegularvariable,whichcanonlystoreonepieceofdata.Thepiecesofdataarestoredsequentiallyinarray“elements”thatarenumbered,startingatzero.So,thefirstvalueisstoredinelementzero,thesecondvalueisstoredinelementone,andsoon.

Anarrayisdeclaredinthesamewayasothervariables,butadditionallythesizeofthearraymustalsobespecifiedinthedeclaration,insquarebracketsfollowingthearrayname.Forexample,thesyntaxtodeclareanarraynamed“nums”tostoresixintegernumberslookslikethis:

int nums[6];

Optionally,anarraycanbeinitializedwhenitisdeclaredbyassigningvaluestoeachelementasacomma-separatedlistenclosedbycurlybrackets(braces).Forexample:

int nums[6]={0,1,2,3,4,5};

Arraynumberingstartsatzero–sothefinalelementinanarrayofsixelementsisnumberfive,notnumbersix.

Anindividualelementcanbereferencedusingthearraynamefollowedbysquarebracketscontainingtheelementnumber.Thismeansthatnums[1]referencesthesecondelementintheexampleabove–notthefirstelement,aselementnumberingstartsatzero.

ArrayscanbecreatedforanyC++datatype,buteachelementmayonlycontaindataofthesamedatatype.Anarrayofcharacterscanbeusedtostoreastringoftextifthefinalelementcontainsthespecial\0nullcharacter.Forexample:

charname[5]={‘m’,‘i’,‘k’,‘e’,‘\0’};

Page 32: C++ Programming in easy steps, 5th Edition

Theentirestringtobereferencedjustbythearrayname.ThisistheprinciplemeansofworkingwithstringsintheClanguage,buttheC++stringclass,introducedinchapterfour,isfarsimpler.

Collectively,theelementsofanarrayareknownasan“index”.Arrayscanhavemorethanoneindex–torepresentmultipledimensions,ratherthanthesingledimensionofaregulararray.Multi-dimensionalarraysofthreeindicesandmoreareuncommon,buttwo-dimensionalarraysareusefultostoregrid-basedinformation,suchascoordinates.Forexample:

int coords[2][3]={{1,2,3},{4,5,6}};

arrays.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertstatementstodeclareandinitializethreevariablearrays//Declaredtheninit ialized.float nums[3];nums[0]=1.5;nums[1]=2.75;nums[2]=3.25;

//Declaredandinit ialized.charname[5]={‘m’,‘i’,‘k’,‘e’,‘\0’};int coords[2][3]={{1,2,3},{4,5,6}};}

Now,insertstatementstooutputspecificelementvaluescout <<“nums[0]:”<<nums[0]<<endl;cout <<“nums[1]:”<<nums[1]<<endl;cout <<“nums[2]:”<<nums[2]<<endl;cout <<“name[0]:”<<name[0]<<endl;cout <<“Text st ring:”<<name<<endl;cout <<“coords[0][2]:”<<coords[0][2]<<endl;

Page 33: C++ Programming in easy steps, 5th Edition

cout <<“coords[1][2]:”<<coords[1][2]<<endl;

Save,compile,andruntheprogramtoseetheoutput

Wherepossible,variablenamesshouldnotbeabbreviations–abbreviatednamesareonlyusedinthisbook’sexamplesduetospacelimitations.

Theloopstructures,introducedinChapterThree,areoftenusedtoiteratearrayelements.

Page 34: C++ Programming in easy steps, 5th Edition
Page 35: C++ Programming in easy steps, 5th Edition

EmployingvectorarraysAvectorisanalternativetoaregulararray,andhastheadvantagethatitssizecanbechangedastheprogramrequires.Likeregulararrays,vectorscanbecreatedforanydatatype,andtheirelementsarealsonumberedstartingatzero.

Inordertousevectorsinaprogram,theC++vectorlibrarymustbeaddedwithan#include<vector>preprocessordirectiveatthestartoftheprogram.Thislibrarycontainsthepredefinedfunctionsinthetablebelow,whichareusedtoworkwithvectors:

Funct ion: Descript ion:

at (number) Getsthevaluecontainedinthespecifiedelementnumber

back() Getsthevalueinthefinalelement

clear() Removesallvectorelements

empty() Returnstrue(1)ifthevectorisempty,orreturnsfalse(0)otherwise

front () Getsthevalueinthefirstelement

pop_back() Removesthefinalelement

push_back(value) Addsafinalelementtotheendofthevector,containingthespecifiedvalue

size() Getsthenumberofelements

Adeclarationtocreateavectorlookslikethis:

vector<data-type>vector-name(size);

Anint vectorwill,bydefaulthaveeachelementautomaticallyinitializedwithazerovalue.Optionally,adifferentinitialvaluecanbespecifiedafterthesizeinthedeclaration,withthissyntax:

vector<data-type>vector-name(size,initial-value);

Thefunctionstoworkwithvectorsaresimplyappendedtothechosenvectornamebythedotoperator.Forexample,togetthesizeofavectornamed“vec”youwouldusevec.size().

Individualvectorelementscanbereferencedusingsquarebracketsaswithregulararrays,suchasvec[3].

Page 36: C++ Programming in easy steps, 5th Edition

vector.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<vector>//Includevectorsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertastatementtodeclareandinitializeavectorarrayofthreeelementsofthevalue100vector<int>vec(3,100);

Now,insertstatementstomanipulatethevectorelementscout <<“Vectorsize:”<<vec.size()<<endl;cout <<“Isempty?:”<<vec.empty()<<endl;cout <<“First element :”<<vec.at (0)<<endl;

vec.pop_back();//Removefinalelement .cout <<“Vectorsize:”<<vec.size()<<endl;cout <<“Finalelement :”<<vec.back()<<endl;

vec.clear();//Removeallelements.cout <<“Vectorsize:”<<vec.size()<<endl;

vec.push_back(200);//Addanelement .cout <<“Vectorsize:”<<vec.size()<<endl;cout <<“First element :”<<vec.front ()<<endl;

Save,compile,andruntheprogramtoseetheoutput

Page 37: C++ Programming in easy steps, 5th Edition

Theexamplehereshowshowtousealooptopopulateavectorwithdifferentinitialvaluesineachelement.

Page 38: C++ Programming in easy steps, 5th Edition
Page 39: C++ Programming in easy steps, 5th Edition

DeclaringconstantsDatathatwillnotchangeduringtheexecutionofaprogramshouldbestoredinaconstantcontainer,ratherthaninavariable.Thisbetterenablesthecompilertocheckthecodeforerrors–iftheprogramattemptstochangethevaluestoredinaconstant,thecompilerwillreportanerrorandthecompilationwillfail.

Aconstantcanbecreatedforanydatatypebyprefixingavariabledeclarationwiththeconstkeyword,followedbyaspace.Typically,constantnamesappearinuppercasetodistinguishthemfrom(lowercase)variablenames.Unlikevariables,constantsmustalwaysbeinitializedinthedeclaration.Forexample,thedeclarationofaconstantforthemathpivaluelookslikethis:

const doublePI=3.1415926536;

Theenumkeywordprovidesahandywaytocreateasequenceofintegerconstantsinaconcisemanner.Optionally,thedeclarationcanincludeanameforthesequenceaftertheenumkeyword.Theconstantnamesfollowasacomma-separatedlistwithinbraces.Forexample,thisdeclarationcreatesasequenceofconstants:

enumsuit {CLUBS,DIAMONDS,HEARTS,SPADES};

Eachoftheconstantswill,bydefault,haveavalueonegreaterthantheprecedingconstantinthelist.Unlessspecified,thefirstconstantwillhaveavalueofzero,thenextavalueofone,andsoon.Aconstantcanbeassignedanyintegervalue,butthenextconstantinthelistwillalwaysincrementitbyone.

Itisoccasionallyconvenienttodefinealistofenumeratedconstantsasa“customdatatype”–byusingthet ypedefkeyword.Thiscanbegintheenumdeclaration,andachosentypenamecanbeaddedattheendofthedeclaration.Forexample,thist ypedefstatementcreatesacustomdatatypenamed“charge”:

t ypedefenum{NEGATIVE,POSIT IVE}charge;

Variablescanthenbecreatedofthecustomdatatypeintheusualway,whichmaylegallybeassignedanyofthelistedconstants.Essentially,thesevariablesactjustlikeanint variable–astheystorethenumericalintegervaluetheassignedconstantrepresents.Forexample,withtheexampleabove,assigningaPOSITIVEconstanttoachargevariableactuallyassignsanintegerofone.

Thetypedefkeywordsimplycreatesanicknameforastructure.

Page 40: C++ Programming in easy steps, 5th Edition

constant.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertstatementstodeclareaconstant,andoutputusingtheconstantvalueconst doublePI=3.1415926536;cout <<“6\”circlecircumference:“<<(PI*6)<<endl;

Next,insertstatementstodeclareanenumeratedlistofconstants,andoutputusingsomeofthoseconstantvaluesenum{RED=1,YELLOW,GREEN,BROWN,BLUE,PINK,BLACK};cout <<“Ishot aredworth:”<<RED<<endl;cout <<“Thenablueworth:”<<BLUE<<endl;cout <<“Totalscored:”<<(RED+BLUE)<<endl;

Now,insertstatementstodeclareacustomdatatypeandoutputitsassignedvaluest ypedefenum{NEGATIVE,POSIT IVE}charge;chargeneut ral=NEGATIVE,live=POSITIVE;cout <<“Neut ralwire:”<<neut ral<<endl;cout <<“Livewire:”<<live<<endl;

Save,compile,andruntheprogramtoseetheoutput

Page 41: C++ Programming in easy steps, 5th Edition

InthePIdeclaration,the*characteristheC++multiplicationoperator,andthebackslashcharacterin\”escapesthequotemarkfromrecognition–sothestringdoesnotgetterminatedprematurely.

Page 42: C++ Programming in easy steps, 5th Edition
Page 43: C++ Programming in easy steps, 5th Edition

Summary• C++isanobject-orientedprogramminglanguagethatisanextensionoftheproceduralC

programminglanguage.

• TheGNUC++CompilerisavailableforWindowsandLinux.

• PreprocessordirectivesareusedtomakefunctionswithinthestandardC++librariesavailabletoaprogram.

• EachC++programmustcontainonemainmethodastheentrypointtotheprogram.

• Statementsdefinetheactionsthattheprogramwillexecute.

• Itisrecommendedthatprogramcodeshouldbewidelycommentedtomakeitspurposeclear.

• Thec++commandcallsthecompiler,andits-ooptionallowsthecommandtospecifythenameofthegeneratedexecutable.

• Avariabledeclarationspecifiesadatatypeandachosennamebywhichthevaluewithinthatvariablecanbereferenced.

• Thecout function,whichispartoftheC++iost reamlibrary,writescontenttothestandardoutputconsole.

• Anarrayisafixedsizevariablethatstoresmultipleitemsofdatainelements,whicharenumberedstartingatzero.

• Thespecial\0charactercanbeassignedtothefinalelementofachararraytoallowittobetreatedasasingletextstring.

• Avectorvariablestoresmultipleitemsofdatainelements,andcanbedynamicallyresized.

• Thevaluestoredinanarrayorvectorelementcanbereferencedusingthatvariable’snameanditsindexnumber.

• Variablevaluesthatareneverchangedbytheprogramshouldbestoredinaconstant.

• Aconstantlistcanbeautomaticallynumberedbytheenumkeywordandgivenatypenamebythet ypedefkeyword.

Page 44: C++ Programming in easy steps, 5th Edition

2

Performingoperations

ThischapterintroducestheC++operatorsanddemonstratestheoperationstheycanperform.

DoingarithmeticAssigningvaluesComparingvaluesAssessinglogicExaminingconditionsEstablishingsizeSettingprecedenceCastingdatatypesSummary

Page 45: C++ Programming in easy steps, 5th Edition
Page 46: C++ Programming in easy steps, 5th Edition

DoingarithmeticThearithmeticaloperatorscommonlyusedinC++programsarelistedinthetablebelow,togetherwiththeoperationtheyperform:

Operator: Operat ion:

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

++ Increment

-- Decrement

Theoperatorsforaddition,subtraction,multiplication,anddivisionactasyouwouldexpect.Caremustbetaken,however,tobracketexpressionswheremorethanoneoperatorisusedtoclarifytheexpression–operationswithininnermostparenthesesareperformedfirst:

a=b*c-d%e/f;//Thisisunclear.

a=(b*c)-((d%e)/f);//Thisisclearer.

The% modulusoperatorwilldividethefirstgivennumberbythesecondgivennumberandreturntheremainderoftheoperation.Thisisusefultodetermineifanumberhasanoddorevenvalue.

Valuesusedwithoperatorstoformexpressionsarecalled“operands”–intheexpression2+3thenumericalvalues2and3aretheoperands.

The++incrementoperatorand--decrementoperatoralterthegivennumberbyoneandreturntheresultingvalue.Thesearemostcommonlyusedtocountiterationsinaloop.Countingup,the++operatorincreasesthevaluebyone,whilecountingdown,the--decrementoperatordecreasesthevaluebyone.

Theincrementanddecrementoperatorscanbeplacedbeforeorafteravaluetodifferenteffect.Ifplacedbeforetheoperand(prefix),itsvalueisimmediatelychanged;ifplacedaftertheoperand(postfix),itsvalueisnotedfirst,thenthevalueischanged.

Page 47: C++ Programming in easy steps, 5th Edition

arithmetic.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertastatementtodeclareandinitializetwointegervariablesint a=8,b=4;

Next,insertstatementstooutputtheresultofeachbasicarithmeticoperationcout <<“Addit ionresult :”<<(a+b)<<endl;cout <<“Subt ract ionresult :”<<(a-b)<<endl;cout <<“Mult iplicat ionresult :”<<(a*b)<<endl;cout <<“Divisionresult :”<<(a/b)<<endl;cout <<“Modulusresult :”<<(a%b)<<endl;

Now,insertstatementstooutputtheresultofbothpostfixandprefixincrementoperationscout <<“Post fixincrement :”<<a++<<endl;cout <<“Post fixresult :”<<a<<endl;cout <<“Prefixincrement :”<<++b<<endl;cout <<“Prefixresult :”<<b<<endl;

Save,compile,andruntheprogramtoseetheoutput

Page 48: C++ Programming in easy steps, 5th Edition

Rememberthataprefixoperatorchangesthevariablevalueimmediately–apostfixoperatorchangesthevaluesubsequently.

Page 49: C++ Programming in easy steps, 5th Edition
Page 50: C++ Programming in easy steps, 5th Edition

AssigningvaluesTheoperatorsthatareusedinC++programmingtoassignvaluesarelistedinthetablebelow.Allexceptthesimple=assignmentoperatorareashorthandformofalongerexpressionsoeachequivalentisgivenforclarity:

Operator: Example: Equivalent :

= a=b a=b

+= a+=b a=(a+b)

-= a-=b a=(a-b)

*= a*=b a=(a*b)

/= a/=b a=(a/b)

%= a%=b a=(a%b)

Intheexampleabove,thevariablenamed“a”isassignedthevaluethatiscontainedinthevariablenamed“b”–sothatbecomesthenewvaluestoredintheavariable.

The+=operatorisusefultoaddavalueontoanexistingvaluethatisstoredintheavariable.

Inthetableexample,the+=operatorfirstaddsthevaluecontainedinvariableatothevaluecontainedinvariableb.Itthenassignstheresulttobecomethenewvaluestoredinvariablea.

Itisimportanttoregardthe=operatortomean“assign”ratherthan“equals”toavoidconfusionwiththe==equalityoperator.

Alltheotheroperatorsworkinthesamewaybymakingthearithmeticaloperationbetweenthetwovaluesfirst,thenassigningtheresultofthatoperationtothefirstvariable–tobecomeitsnewstoredvalue.

Withthe%=operator,thefirstoperandaisdividedbythesecondoperandb,thentheremainderofthatoperationisassignedtotheavariable.

Eachassignmentoperationisdemonstratedintheprogrambelow.

Page 51: C++ Programming in easy steps, 5th Edition

assign.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertastatementdeclaringtwointegervariablesint a,b;

Next,insertstatementstooutputsimpleassignedvaluescout <<“Assignvalues:”;cout <<“a=“<<(a=8)<<““;cout <<“b=“<<(b=4);

Now,insertstatementstooutputcombinedassignedvaluescout <<endl<<“Add&assign:”;cout <<“a+=b(8+=4)a=“<<(a+=b);cout <<endl<<“Subt ract &assign:”;cout <<“a-=b(12-=4)a=“<<(a-=b);cout <<endl<<“Mult iply&assign:”;cout <<“a*=b(8*=4)a=“<<(a*=b);cout <<endl<<“Divide&assign:”;cout <<“a/=b(32/=4)a=“<<(a/=b);cout <<endl<<“Modulus&assign:”;cout <<“a%=b(8%=4)a=“<<(a%=b);

Save,compile,andruntheprogramtoseetheoutput

Page 52: C++ Programming in easy steps, 5th Edition

Unlikethe=assignoperator,the==equalityoperatorcomparesoperandsandisdescribedhere.

Page 53: C++ Programming in easy steps, 5th Edition
Page 54: C++ Programming in easy steps, 5th Edition

ComparingvaluesTheoperatorsthatarecommonlyusedinC++programmingtocomparetwonumericalvaluesarelistedinthetablebelow:

Operator: Comparat ivetest :

== Equality

!= Inequality

> Greaterthan

< Lessthan

>= Greaterthanorequalto

<= Lessthanorequalto

The==equalityoperatorcomparestwooperandsandwillreturnt rue(1)ifbothareequalinvalue,otherwiseitwillreturnafalse(0)value.Ifbotharethesamenumber,theyareequal,orifbotharecharacters,theirASCIIcodevaluesarecomparednumerically.Conversely,the!=inequalityoperatorreturnst rue(1)iftwooperandsarenotequal,usingthesamerulesasthe==equalityoperator,otherwiseitreturnsfalse(0).Equalityandinequalityoperatorsareusefulintestingthestateoftwovariablestoperformconditionalbranchinginaprogram.

A-ZuppercasecharactershaveASCIIcodevalues65-90anda-zlowercasecharactershaveASCIIcodevalues97-122.

The>“greaterthan”operatorcomparestwooperandsandwillreturnt rue(1)ifthefirstisgreaterinvaluethanthesecond,oritwillreturnfalse(0)ifitisequalorlessinvalue.The<“lessthan”operatormakesthesamecomparisonbutreturnst rue(1)ifthefirstoperandislessinvaluethanthesecond,otherwiseitreturnsfalse(0).A>“greaterthan”or<“lessthan”operatorisoftenusedtotestthevalueofaniterationcounterinaloop.

Addingthe=operatoraftera>“greaterthan”or<“lessthan”operatormakesitalsoreturnt rue(1)ifthetwooperandsareexactlyequalinvalue.

Eachcomparisonoperationisdemonstratedintheprogrambelow.

Page 55: C++ Programming in easy steps, 5th Edition

comparison.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoincludeandanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertstatementstodeclareandinitializevariablesthatcanconverttoBooleansint nil=0,num=0,max=1;charcap=‘A’,low=‘a’;

Next,insertstatementstooutputequalitycomparisonsofintegersandcharacterscout <<“Equalitycomparisons:”;cout <<“(0==0)”<<(nil==num)<<“(t rue)”;cout <<“(A==a)”<<(cap==low)<<“(false)”;

Now,insertstatementstooutputallothercomparisonscout <<endl<<“Inequalitycomparison:”;cout <<“(0!=1)”<<(nil!=max)<<“(t rue)”;cout <<endl<<“Greatercomparison:”;cout <<“(0>1)”<<(nil>max)<<“(false)”;cout <<endl<<“Lessercomparison:”;cout <<“(0<1)”<<(nil<max)<<“(t rue)”;cout <<endl<<“Greaterorequalcomparison:”;cout <<“(0>=0)”<<(nil>=num)<<“(t rue)”;cout <<endl<<“Lesserorequalcomparison:”;cout <<“(1<=0)”<<(max<=num)<<“(false)”;

Save,compile,andruntheprogramtoseetheoutput

Page 56: C++ Programming in easy steps, 5th Edition

TheASCIIcodevalueforuppercase“A”is65,butforlowercase“a”it’s97–sotheircomparisonherereturnsfalse(0).

Page 57: C++ Programming in easy steps, 5th Edition
Page 58: C++ Programming in easy steps, 5th Edition

AssessinglogicThelogicaloperatorsmostcommonlyusedinC++programmingarelistedinthetablebelow:

Operator: Operat ion:

&& LogicalAND

|| LogicalOR

! LogicalNOT

ThelogicaloperatorsareusedwithoperandsthathaveBooleanvaluesoft rueorfalse,orarevaluesthatconverttot rueorfalse.

Thelogical&&ANDoperatorwillevaluatetwooperandsandreturnt rueonlyifbothoperandsthemselvesaret rue.Otherwise,the&&operatorwillreturnfalse.Thisisusedinconditionalbranchingwherethedirectionofaprogramisdeterminedbytestingtwoconditions–ifbothconditionsaresatisfied,theprogramwillgoinacertaindirection,otherwiseitwilltakeadifferentdirection.

Wherethereismorethanoneoperandeachexpressionmustbeenclosedbyparentheses.

Unlikethe&&ANDoperatorthatneedsbothoperandstobet rue,the||ORoperatorwillevaluateitstwooperandsandreturnt rueifeitheroneoftheoperandsitselfreturnst rue.Ifneitheroperandreturnst ruethenthe||ORoperatorwillreturnfalse.ThisisusefulinC++programmingtoperformacertainactionifeitheroneoftwotestconditionshasbeenmet.

Thethirdlogical!NOToperatorisaunaryoperatorthatisusedbeforeasingleoperand.Itreturnstheinversevalueofthegivenoperand,soifthevariableahadavalueoft rue,then!awouldhaveavalueoffalse.The!NOToperatorisusefulinC++programstotogglethevalueofavariableinsuccessiveloopiterationswithastatementlikea=!a.Thisensuresthatoneachpassthevalueischanged,likeflickingalightswitchonandoff.

Page 59: C++ Programming in easy steps, 5th Edition

Theterm“Boolean”referstoasystemoflogicalthoughtdevelopedbytheEnglishmathematicianGeorgeBoole(1815-1864).

InC++programs,azerorepresentstheBooleanfalsevalueandanynon-zerovalue,suchasone,representstheBooleant ruevalue.

Eachlogicaloperationisdemonstratedintheprogrambelow.

logic.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,declareandinitializetwointegervariables–withvaluesthatcanrepresentBooleanvaluesint a=1,b=0;

InsertstatementstooutputtheresultofANDevaluationscout <<“ANDlogic:”<<endl;cout <<“(a&&a)”<<(a&&a)<<“(t rue)”;cout <<“(a&&b)”<<(a&&b)<<“(false)”;cout <<“(b&&b)”<<(b&&b)<<“(false)”<<endl;

InsertstatementstooutputtheresultofORevaluationscout <<endl<<“ORlogic:”<<endl;cout <<“(a||a)”<<(a||a)<<“(t rue)”;cout <<“(a||b)”<<(a||b)<<“(t rue)”;cout <<“(b||b)”<<(b||b)<<“(false)”<<endl;

Page 60: C++ Programming in easy steps, 5th Edition

InsertstatementstooutputtheresultofNOTevaluations

cout <<endl<<“NOTlogic:”<<endl;cout <<“a=“<<a<<“!a=“<<!a<<““;cout <<“b=“<<b<<“!b=“<<!b<<endl;

Save,compile,andruntheprogramtoseetheoutput

Noticethat0&&0returns0,not1–demonstratingthemaxim“twowrongsdon’tmakearight”.

Page 61: C++ Programming in easy steps, 5th Edition
Page 62: C++ Programming in easy steps, 5th Edition

ExaminingconditionsPossiblytheC++programmer’smostfavoritetestoperatoristhe?:“ternary”operator.Thisoperatorfirstevaluatesanexpressionforat rueorfalsecondition,thenreturnsoneoftwospecifiedvaluesdependingontheresultoftheevaluation.Forthisreasonitisalsoknownasthe“conditional”operator.

The?:ternaryoperatorhasthissyntax:

(test-expression)?if-true-return-this:if-false-return-this;

Althoughtheternaryoperatorcaninitiallyappearalittleconfusing,itiswellworthbecomingfamiliarwiththisoperatorasitcanexecutepowerfulprogrambranchingwithminimalcode.Forexample,tobranchwhenavariableisnotavalueofone:

(var!=1)?if-true-do-this:if-false-do-this;

TheternaryoperatoriscommonlyusedinC++programmingtoassignthemaximumorminimumvalueoftwovariablestoathirdvariable.Forexample,toassignaminimumlikethis:

c=(a<b)?a:b;

Theexpressioninparenthesesreturnst ruewhenthevalueofvariableaislessthanthatofvariableb–sointhiscase,thelesservalueofvariableagetsassignedtovariablec.

Similarly,replacingthe<lessthanoperatorinthetestexpressionwiththe>greaterthanoperatorwouldassignthegreatervalueofvariablebtovariablec.

Anothercommonuseoftheternaryoperatorincorporatesthe% modulusoperatorinthetestexpressiontodeterminewhetherthevalueofavariableisanoddnumberoranevennumber:

(var%2!=0)?if-true(odd)-do-this:if-false(even)-do-this;

Theternaryoperatorhasthreeoperands–theonebeforethe?,andthosebeforeandafterthe:.

Wheretheresultofdividingthevariablevaluebytwodoesleavearemainder,thenumberisodd–wherethereisnoremainder,thenumberiseven.Thetestexpression(var%2==1)wouldhavethesameeffectbutitispreferabletotestforinequality–it’seasiertospotwhensomethingisdifferentthanwhenit’sidentical.

Theternaryoperatorisdemonstratedintheprogrambelow.

Page 63: C++ Programming in easy steps, 5th Edition

ternary.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertstatementsdeclaringthreeintegervariables,andinitializingtwoofthemint a,b,max;a=1,b=2;

Insertstatementstooutputthevalueandparityofthefirstexaminedvariablecout <<“Variableavalueis:”;cout <<((a!=1)?“not one,“:“one,“);cout <<((a%2!=0)?“odd”:“even”);

Next,insertstatementstooutputthevalueandparityofthesecondexaminedvariablecout <<endl<<“Variablebvalueis:”;cout <<((b!=1)?“not one,“:“one,“);cout <<((b%2!=0)?“odd”:“even”);

Now,insertstatementstooutputthegreaterofthetwostoredvariablevaluesmax=(a>b)?a:b;cout <<endl<<“Greatervalueis:”<<max<<endl;

Save,compileandruntheprogramtoseetheoutput

Page 64: C++ Programming in easy steps, 5th Edition

Theternaryoperatorcanreturnvaluesofanydatatype–numbers,strings,Booleanvalues,etc.

Page 65: C++ Programming in easy steps, 5th Edition
Page 66: C++ Programming in easy steps, 5th Edition

EstablishingsizeDeclarationofavariableallocatessystemmemorywherevaluesassignedtothatvariablewillbestored.Theamountofmemoryallocatedforthisisdeterminedbyyoursystemandthedatatype.

Typically,anint datatypeiscreatedasa“long”valuebydefault,whichcanstorevaluesfrom+2,147,483,647to-2,147,483,648.Ontheotherhand,iftheint datatypeiscreatedasa“short”valuebydefault,itcanonlystorevaluesfrom+32,767to-32,768.

Thepreferredrangecanbeexplicitlyspecifiedwhendeclaringthevariablebyprefixingtheint keywordwithashort orlongqualifier.Theshort int isusefultosavememoryspacewhenyouaresurethelimitedrangewillneverbeexceeded.

Whenanint variableisdeclared,itcanbydefaultcontaineitherpositiveornegativeintegers,whichareknownas“signed”values.Ifthevariablewillalwayscontainonlypositiveintegers,itcanbequalifiedasunsignedtoincreaseitsmaximumpossiblevalue.Typically,anunsignedshort int hasarangefromzeroto65,535andanunsignedlongint hasarangefromzeroto4,294,967,295.

ThememorysizeofanyvariablecanbediscoveredusingtheC++sizeofoperator.Thenameofthevariabletobeexaminedcanbespecifiedinoptionalparenthesesfollowingthesizeofoperatorname.Forexample,toexamineavariablenamed“var”:

sizeof(var);//Alternat ivelyyoucanuse“sizeofvar;”.

Thesizeofoperatorwillreturnanintegerthatisthenumberofbytesallocatedtostoredatawithinthenamedvariable.

Althoughsizeofisanoperatorthatdoesnotstrictlyneedparentheses,itiscommonlyseenwiththem–asifitwasafunction,likemain().

Simpledatatypes,suchascharandbool,onlyneedasinglebyteofmemorytostorejustonepieceofdata.Longernumericvaluesneedmorememory,accordingtotheirpossiblerange–determinedbydatatypeandqualifiers.

Thememoryallocatedtoanarrayissimplyamultipleofthatallocatedtoasinglevariableofitsdatatype,accordingtoitsnumberofelements.Forexample,anint arrayof50elementswillallocate50timesthememoryallocatedtoasingleint variable.

Thesizeofoperatorisdemonstratedintheprogrambelow.

Page 67: C++ Programming in easy steps, 5th Edition

sizeof.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}Inthemainfunction,insertstatementsdeclaringvariablesofvariousdatatypesint num; int nums[50]; float decimal;boolisTrue; unsignedint max; charlet ter;doublepi; short int number; charlet ters[50];

Next,insertstatementstooutputthebytesizeofeachintegervariablecout <<“int size:”<<sizeof(num)<<endl;cout <<“50int size:”<<sizeof(nums)<<endl;cout <<“short int size:”<<sizeof(number)<<endl;cout <<“unsignedint size:”<<sizeof(max)<<endl;

Now,insertstatementstooutputthesizeofothervariablescout <<“doublesize:”<<sizeof(pi)<<endl;cout <<“float size:”<<sizeof(decimal)<<endl;cout <<“charsize:”<<sizeof(let ter)<<endl;cout <<“50charsize:”<<sizeof(let ters)<<endl;cout <<“boolsize:”<<sizeof(isTrue)<<endl;

Save,compileandruntheprogramtoseetheoutput

Page 68: C++ Programming in easy steps, 5th Edition

Here,theintdatatypeiscreatedasalongtypebydefault–yoursystemmaybedifferent.

Page 69: C++ Programming in easy steps, 5th Edition
Page 70: C++ Programming in easy steps, 5th Edition

SettingprecedenceOperatorprecedencedeterminestheorderinwhichC++evaluatesexpressions.Forexample,intheexpressiona=6+8*3,theorderofprecedencedeterminesthatmultiplicationiscompletedfirst.

Thetablebelowlistsoperatorprecedenceindescendingorder–thoseonthetoprowhavehighestprecedence,thoseonlowerrowshavesuccessivelylowerprecedence.TheorderinwhichC++evaluatesexpressionscontainingmultipleoperatorsofequalprecedenceisdeterminedby“operatorassociativity”–groupingoperandswiththeoneontheleft(LTR)orontheright(RTL).

The*multiplyoperatorisonahigherrowthanthe+additionoperator–sointheexpressiona=6+8*3,multiplicationiscompletedfirst,beforetheaddition.

Operator: Direct ion:

() Functioncall [] ArrayindexLTR

-> Classpointer . Classmember

! LogicalNOT * Pointer

RTL-- Decrement ++ Increment

+ Positivesign - Negativesign

sizeof Sizeof & Addressof

* Multiply / DivideLTR

% Modulus

+ Add - Subtract LTR

<= Lessorequal < LessthanLTR

>= Greaterorequal > Greaterthan

== Equality != Inequality LTR

&& LogicalAND LTR

|| LogicalOR LTR

?: Ternary RTL

Page 71: C++ Programming in easy steps, 5th Edition

+=-=*=/=%=Assignments RTL

, Comma LTR

The->classpointerandthe.classmemberoperatorsareintroducedlaterinthisbook–buttheyareincludedhereforcompleteness.

Inadditiontotheoperatorsinthistablethereareanumberof“bitwise”operators,whichareusedtoperformbinaryarithmetic.Thisisoutsidethescopeofthisbook,butthereisasectiondevotedtobinaryarithmeticinCProgrammingineasysteps.ThoseoperatorsperforminjustthesamewayinC++.

Operatorprecedenceisdemonstratedintheprogrambelow.

precedence.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontinuingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,declareanintegervariableinitializedwiththeresultofanexpressionusingdefaultprecedence,thenoutputtheresultint num=1+4*3;cout <<endl<<“Default order:”<<num<<endl;

Next,assigntheresultofthisexpressiontothevariableusingexplicitprecedence,thenoutputtheresultnum=(1+4)*3;cout <<“Forcedorder:”<<num<<endl<<endl;

Assigntheresultofadifferentexpressiontothevariableusingdirectionprecedence,thenoutputtheresultnum=7-4+2;

Page 72: C++ Programming in easy steps, 5th Edition

cout<<“Default direct ion:”<<num<<endl;

Now,assigntheresultofthisexpressiontothevariableusingexplicitprecedence,thenoutputtheresultnum=7-(4+2);cout <<“Forceddirect ion:”<<num<<endl;

Save,compileandruntheprogramtoseetheoutput

Donotrelyupondefaultprecedenceasitmayvarybetweencompilers–alwaysuseparenthesestoclarifyexpressions.

Page 73: C++ Programming in easy steps, 5th Edition
Page 74: C++ Programming in easy steps, 5th Edition

CastingdatatypesAnydatastoredinavariablecanbeforced(coerced)intoavariableofadifferentdatatypebyaprocessknownas“casting”.Thecaststatementsimplystatesthedatatypetowhichthevalueshouldbecastinparenthesesprecedingthenameofthevariablecontainingthedatatobecast.Socastingsyntaxlookslikethis:

variable-name=(data-type)variable-name;

ThisisthetraditionalformofcastingthatisalsofoundintheCprogramminglanguage.AneweralternativeavailableinC++usesangledbracketswiththestat ic_cast keywordlikethis:

variable-name=stat ic_cast <data-type>variable-name;

Thenewerversionallowscaststobemoreeasilyidentifiedinsourcecodebyavoidingtheuseofparentheses,whichcaneasilybeconfusedwithparenthesesinexpressions.Thenewerformofcastingispreferred,buttheolderformisstillwidelyfound.

Castingisoftennecessarytoaccuratelystoretheresultofanarithmeticoperation,becausedividingoneintegerbyanotherintegerwillalwaysproduceanintegerresult.Forexample,theintegerdivision7/2producesthetruncatedintegerresultof3.

Tostoretheaccuratefloating-pointresultwouldrequiretheresultbecastintoasuitabledatatype,suchasafloat ,likethis:

float result =(float )7/2;

Oralternativelyusingthenewerformofcast:

float result =stat ic_cast <float >7/2;

Theresultofdividinganintegerbyanotherintegeristruncated,notrounded–soaresultof9.9wouldbecome9.

Ineithercase,itshouldbenotedthatoperatorprecedencecaststhefirstoperandintothespecifieddatatypebeforeimplementingthearithmeticoperation,sothestatementcanbestbewrittenas:

float result =stat ic_cast <float >(7)/2;

Bracketingtheexpressionas(7/2)wouldperformthearithmeticfirstonintegers,sotheintegerresultwouldbetruncatedbeforebeingcastintothefloat variable–notthedesiredeffect!

Page 75: C++ Programming in easy steps, 5th Edition

CastingwithboththeolderC-styleformandthenewerC++formisdemonstratedintheprogrambelow.

cast.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertstatementstodeclareandinitializeinteger,character,andfloating-pointvariablesint num=7,factor=2;charlet ter=‘A’;float result =0.0;

Outputtheresultofaplainintegerdivisioncout <<“Integerdivision:”<<(num/factor)<<endl;

Now,castthesamedivisionintoafloating-pointvariableandoutputthatresultresult =(float )(num)/factor;cout <<“Cast divisionfloat :”<<result <<endl;

Next,castacharactervariableintoanintegervariableandoutputthatvaluenum=stat ic_cast <int>(let ter);cout <<“Cast characterint :”<<num<<endl;

Castanintegerintoacharactervariableandoutputitlet ter=stat ic_cast <char>(70);cout <<“Cast integerchar:”<<let ter<<endl;

Save,compileandruntheprogramtoseetheoutput

Page 76: C++ Programming in easy steps, 5th Edition

ASCII(pronounced“askee”)istheAmericanStandardCodeforoutInformationInterchange,whichistheacceptedstandardforplaintext.InASCII,charactersarerepresentednumericallywithintherange0-127.Uppercase‘A’is65,sothatintegervaluegetscastintoanintvariable.

Page 77: C++ Programming in easy steps, 5th Edition
Page 78: C++ Programming in easy steps, 5th Edition

Summary• Arithmeticaloperatorscanformexpressionswithtwooperandsforaddition+,subtraction

-,multiplication*,division/,ormodulus% .

• Increment++anddecrement--operatorsmodifyasingleoperandbyavalueofone.

• Theassignment=operatorcanbecombinedwithanarithmeticaloperatortoperformanarithmeticalcalculation,thenassignitsresult.

• Comparisonoperatorscanformexpressionscomparingtwooperandsforequality==,inequality!=,greater>,lesser<,greaterorequal>=,andlesserorequal<=values.

• Logical&&and||operatorsformexpressionsevaluatingtwooperandstoreturnaBooleanvalueoftrueorfalse.

• Thelogical!operatorreturnstheinverseBooleanvalueofasingleoperand.

• Aternary?:operatorevaluatesagivenBooleanexpression,thenreturnsoneoftwooperandsdependingonitsresult.

• Thesizeofoperatorreturnsthememorybytesizeofavariable.

• Anint variablemaybequalifiedasashort typeforsmallernumbers,orasalongtypeforlargenumbers.

• Whereanint variablewillonlystorepositivenumbers,itmaybequalifiedasunsignedtoextenditsnumericrange.

• Itisimportanttoexplicitlysetoperatorprecedenceincomplexexpressionsbyaddingparentheses().

• Datastoredinavariablecanbeforcedintoavariableofadifferentdatatypebythecastingprocess.

• C++supportstraditionalC-stylecastsandthenewerformofcaststhatusethestat ic_castkeyword.

Page 79: C++ Programming in easy steps, 5th Edition

3

Makingstatements

ThischapterdemonstratesC++conditionalstatements,whichallowprogramstobranchindifferentdirections,and

introducesC++functionstructures.

BranchingwithifSwitchingbranchesLoopingforLoopingwhileDeclaringfunctionsPassingargumentsOverloadingfunctionsOptimizingfunctionsSummary

Page 80: C++ Programming in easy steps, 5th Edition
Page 81: C++ Programming in easy steps, 5th Edition

BranchingwithifTheC++ifkeywordperformsthebasicconditionaltestthatevaluatesagivenexpressionforaBooleanvalueoft rueorfalse–anditssyntaxlookslikethis:

if(test-expression){statements-to-execute-when-true}

Thebracesfollowingthetestmaycontainoneormorestatements,eachterminatedbyasemi-colon,butthesewillonlybeexecutedwhentheexpressionisfoundtobet rue.Whenthetestisfoundtobefalse,theprogramproceedstoitsnexttask.

Optionally,anifstatementcanofferalternativestatementstoexecutewhenthetestfailsbyappendinganelsestatementblockaftertheifstatementblock,likethis:

if(test-expression){statements-to-execute-when-true}else{statements-to-execute-when-false}

Wherethereisonlyonestatementtoexecutewhenthetestsucceeds,thebracesmaybeomitted–butretainingthemaidscodeclarity.

Totesttwoconditions,thetestexpressionmayusethe&&operator.Forexample,if((num>5)&&(let ter==‘A’)).Alternatively,anifstatementcanbe“nested”withinanotherifstatement,sothosestatementsintheinnerstatementblockwillonlybeexecutedwhenbothtestssucceed–butstatementsintheouterstatementblockwillbeexecutediftheoutertestsucceeds.

ifelse.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>

Page 82: C++ Programming in easy steps, 5th Edition

usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertstatementstodeclareandinitializetwovariablesint num=8;charlet ter=‘A’;

Next,insertanif-elsestatementthatteststheintegervariablevalueandoutputsanappropriateresponseif(num>5){cout <<“Numberexceedsfive”<<endl;}else{cout <<“Numberisfiveorless”<<endl;}

Intheifstatementblock,insertanestedifstatementthatteststhecharactervariablevalueandoutputswhenmatchedif(let ter==‘A’){cout <<“Let terisA”<<endl;}

Save,compileandruntheprogramtoseebothtestssucceed

Editthecharactervariabledeclarationtochangeitsvaluecharlet ter=‘B’;

Save,compile,andruntheprogramoncemoretoseeonlytheoutertestsucceed–executingtheouterifstatement

Edittheintegervariabledeclarationtochangeitsvalueint num=3;

Save,compile,andruntheprogramagaintoseebothtestsnowfail–executingtheouterelsestatement

Page 83: C++ Programming in easy steps, 5th Edition

ShorthandcanbeusedwhentestingaBooleanvalue–sotheexpressionif(flag==true)canbewrittenasif(flag).

Avoidnestingmorethanthreelevelsofifstatements–toavoidconfusionanderrors.

Page 84: C++ Programming in easy steps, 5th Edition
Page 85: C++ Programming in easy steps, 5th Edition

SwitchingbranchesTheifandelsekeywords,introducedabove,allowprogramstobranchinaparticulardirectionaccordingtotheresultofatestcondition,andcanbeusedtorepeatedlytestavariabletomatchavalue.Forexample,testingforaninteger:

if(num==1){cout <<“Monday”;}elseif(num==2){cout <<“Tuesday”;}elseif(num==3){cout <<“Wednesday”;}elseif(num==4){cout <<“Thursday”;}elseif(num==5){cout <<“Friday”;}

Theprogramwillbranchinthedirectionofthematch.

Conditionalbranchingwithlongif-elsestatementscanoftenbemoreefficientlyperformedusingaswitchstatementinstead,especiallywhenthetestexpressionevaluatesonevariable.

Theswitchstatementworksinanunusualway.Ittakesagivenvariablevalue,thenseeksamatchingvalueamonganumberofcasestatements.Statementsassociatedwiththematchingcasestatementvaluewillthenbeexecuted.

Whennomatchisfound,nocasestatementswillbeexecuted,butyoumayaddadefaultstatementafterthefinalcasestatementtospecifystatementstobeexecutedwhennomatchisfound.

Itisimportanttofolloweachcasestatementwiththebreakkeyword,tostoptheprogramproceedingthroughtheswitchblockafterallstatementsassociatedwiththematchedcasevaluehavebeenexecuted–unlessthatispreciselywhatyourequire.Forexample,onestatementforeachblockofthreevalueslikethis:

switch(variable-name){

casevalue1;casevalue2;casevalue3;statements-to-be-executed;break;

casevalue4;casevalue5;casevalue6;statements-to-be-executed;break;

}

Usually,eachcasestatementwillhaveitsownsetofstatementstoexecuteandbeterminatedbyabreak,asintheprogrambelow.

Page 86: C++ Programming in easy steps, 5th Edition

Missingbreakkeywordsarenotsyntaxerrors–ensurethatallintendedbreaksarepresentaftercasestatements.

switch.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertastatementtodeclareandinitializeanintegervariablewithavaluetobematchedint num=3;

Next,insertaswitchstatementtoseekamatchswitch(num){

case1:cout <<num<<“:Monday”;break;case2:cout <<num<<“:Tuesday”;break;case3:cout <<num<<“:Wednesday”;break;case4:cout <<num<<“:Thursday”;break;case5:cout <<num<<“:Friday”;break;

}

Intheswitchstatement,insertadefault statementafterthefinalcasestatementdefault :cout <<num<<“:Weekendday”;

Save,compile,andruntheprogramtoseetheoutput

Now,edittheintegervariabledeclarationtochangeitsvalue,thensave,compileandruntheprogramoncemoreint num=6;

Page 87: C++ Programming in easy steps, 5th Edition

Noticethatadefaultstatementdoesnotneedtobefollowedbyabreakkeyword–becauseadefaultstatementalwaysappearslastinaswitchstatement.

Page 88: C++ Programming in easy steps, 5th Edition
Page 89: C++ Programming in easy steps, 5th Edition

LoopingforAloopisapieceofcodeinaprogramthatautomaticallyrepeats.Onecompleteexecutionofallstatementscontainedwithintheloopblockisknownasan“iteration”or“pass”.

Thenumberofiterationsmadebyaloopiscontrolledbyaconditionaltestmadewithintheloop.Whilethetestedexpressionremainst rue,theloopwillcontinue–untilthetestedexpressionbecomesfalse,atwhichtimetheloopends.

ThethreetypesofloopstructuresinC++programmingareforloops,whileloops,anddo-whileloops.Perhapsthemostcommonlyusedloopistheforloop,whichhasthissyntax:

for(initializer;test-expression;incrementer){statements}

Theinitializersetsthestartingvalueforacounterofthenumberofiterationsmadebytheloop.Anintegervariableisusedforthispurposeandistraditionallynamed“i”.

Uponeachiterationoftheloop,thetestexpressionisevaluated,andthatiterationwillonlycontinuewhilethisexpressionist rue.Whenthetestedexpressionbecomesfalse,theloopendsimmediatelywithoutexecutingthestatementsagain.Oneachiterationthecounterisincrementedthenthestatementsexecuted.

Loopsmaybenestedwithinotherloops–sothattheinnerloopwillfullyexecuteitsiterationsoneachiterationoftheouterloop.

forloop.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

Page 90: C++ Programming in easy steps, 5th Edition

}

Inthemainfunction,insertastatementtodeclareanintegervariabletobeusedasaloopiterationcounterint i;

Next,insertaforlooptooutputthecountervalueoneachofthreeiterationsfor(i=1;i<4;i++){

cout <<“Loopiterat ion:”<<i<<endl;}

Save,compile,andruntheprogramtoseetheoutput

Now,editthevariabledeclarationtoaddasecondcounterint i,j;//Integervariable“j”added.

Insidetheforloopblock,aftertheoutputstatementaddaninnerlooptooutputitscountervalueoneachiterationfor(j=1;j<4;j++){cout <<“Innerloopiterat ion:“<<j<<endl;}

Save,compile,andruntheprogramagaintoseetheinnerloopfullyexecuteoneachiterationoftheouterloop

Alternatively,aforloopcountercancountdowncountervalueoneachby

Page 91: C++ Programming in easy steps, 5th Edition

decrementingtheiterationusingi--insteadofthei++incrementer.

Onthethirditerationoftheseloops,theincrementerincreasesthecountervaluetofour–sowhenitisnextevaluated,thetestreturnsfalseandtheloopends.

Page 92: C++ Programming in easy steps, 5th Edition
Page 93: C++ Programming in easy steps, 5th Edition

LoopingwhileAnalternativetotheforloop,introducedabove,usesthewhilekeyword,followedbyanexpressiontobeevaluated.Whentheexpressionist rue,statementscontainedwithinbracesfollowingthetestexpressionwillbeexecuted.Theexpressionwillthenbeevaluatedagain,andthewhileloopwillcontinueuntiltheexpressionisfoundtobefalse.

Theloop’sstatementblockmustcontaincodethatwillaffectthetestedexpressioninordertochangetheevaluationresulttofalse,otherwiseaninfiniteloopiscreatedthatwilllockthesystem!Whenthetestedexpressionisfoundtobefalseuponitsfirstevaluation,thewhileloop’sstatementblockwillneverbeexecuted.

Ifyouaccidentallystartrunninganinfiniteloop,presstheCtrl+Ckeystoterminatetheprocess.

Asubtlevariationofthewhileloopplacesthedokeywordbeforetheloop’sstatementblockandawhiletestafterit,withthissyntax:

do{statements-to-be-executed}while(t est -expression);

Inado-whileloop,thestatementblockwillalwaysbeexecutedatleastonce–becausetheexpressionisnotevaluateduntilafterthefirstiterationoftheloop.

Abreakstatementcanbeincludedinanykindoflooptoimmediatelyterminatetheloopwhenatestconditionismet.Thebreakensuresnofurtheriterationsofthatloopwillbeexecuted.

Similarly,acont inuestatementcanbeincludedinanykindoflooptoimmediatelyterminatethatparticulariterationoftheloopwhenatestconditionismet.Thecont inuestatementallowsthelooptoproceedtothenextiteration.

while.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<vector>//Includevectorsupport .# include<iost ream>usingnamespacestd;

Page 94: C++ Programming in easy steps, 5th Edition

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,insertstatementstodeclareanintegervectorandanintegervariableloopcountervector<int>vec(10);int i=0;

Next,insertawhilelooptoassignacountervaluetoanelementofthevectoroneachiterationwhile(i<vec.size()){

i++;//Increment thecounter.vec[i-1]=i;//Assigncount toelement .cout <<“|”<<vec.at (i-1);

}

Savecompileandruntheprogramtoseetheoutput

Editthewhilelooptoaddacont inuestatementimmediatelyaftertheincrementertomaketheloopskipitsthirditerationif(i==3){cout <<“|Skipped”;cont inue;}

Afterthecont inuestatement,nowaddabreakstatement,tomaketheloopquitonitseighthiterationif(i==8){cout <<endl<<“Done”;break;}

Save,compile,andruntheprogramoncemoretoseetheloopnowomitssomeiterations

Page 95: C++ Programming in easy steps, 5th Edition

Thevectorlibrarymustbeincludedwithapreprocessordirectiveinthisexample.

Thepositionofbreakandcontinuestatementsisimportant–theymustappearaftertheincrementer,toavoidcreatinganinfiniteloop,butbeforeotherstatementsthataffecttheprogramtoavoidexecutingthosestatements.

Page 96: C++ Programming in easy steps, 5th Edition
Page 97: C++ Programming in easy steps, 5th Edition

DeclaringfunctionsFunctionsencloseasectionofcodethatprovidesspecificfunctionalitytotheprogram.Whenafunctioniscalledfromthemainprogram,itsstatementsareexecutedand,optionally,avaluecanbereturnedtothemainprogramuponcompletion.Therearethreemainbenefitstousingfunctions:

• Functionsmakeprogramcodeeasiertounderstandandmaintain.

• Triedandtestedfunctionscanbere-usedbyotherprograms.

• Severalprogrammerscandividetheworkloadinlargeprojectsbyworkingondifferentfunctionsoftheprogram.

DeclaringfunctionsEachfunctionisdeclaredearlyintheprogramcodeasa“prototype”,comprisingadatatypeforthevalueitwillreturnandthefunctionnamefollowedbyparentheses,whichmayoptionallycontainalistof“argument”datatypesofpassedvaluesitmayuse.Thesyntaxofafunctionprototypedeclarationlookslikethis:

return-data-typefunction-name(arguments-data-type-list);

Strictlyspeaking,theargumentsinafunctionprototypeareknownasits“formalparameters”.

Forexample,afunctionnamed“computeArea”thatreturnsafloat valueandispassedtwofloat argumentsisdeclaredas:

float computeArea(float ,float );

DefiningfunctionsThefunction’sdefinitionappearslaterintheprogramcodeandcomprisesarepeatoftheprototype,plustheactualfunctionbody.Thefunctionbodyisthestatementstobeexecutedwheneverthefunctioniscalled,containedwithinapairofbraces.

Page 98: C++ Programming in easy steps, 5th Edition

Usethevoidkeywordifthefunctionwillreturnnovaluetothecaller.

Itisimportanttorecognizethatthecompilerchecksthefunctiondefinitionagainsttheprototype,sotheactualreturneddatatypemustmatchthatspecifiedintheprototype,andanysuppliedargumentsmustmatchinbothnumberanddatatype.Compilationfailsifthedefinitiondoesnotmatchtheprototype.AsimplecomputeAreadefinitionmightlooklikethis:

float computeArea(float width,float height ){

return(width*height );}

VariablescopeVariablesthataredeclaredinafunctioncanonlybeusedlocallywithinthatfunction,andarenotaccessiblegloballyforuseinotherfunctions.Thislimitationisknownas“variablescope”.

scope.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Next,declaretwosimplefunctionprototypesfloat bodyTempC();float bodyTempF();

Now,addamainfunctioncontainingcallstoeachfunctionandafinalreturnstatementint main(){

cout <<“Cent igrade:”<<bodyTempC()<<endl;cout <<“Fahrenheit :”<<bodyTempF()<<endl;return0;

}

Afterthemainfunction,definebothotherfunctions–toeachreturnthevalueofalocal“temperature”variablefloat bodyTempC(){

float temperature=37.0;returntemperature;

Page 99: C++ Programming in easy steps, 5th Edition

}

float bodyTempF(){

float temperature=98.6;returntemperature;

}

Save,compile,andruntheprogramtoseetheoutput

Variablesofthesamenamedonotconflictwhentheyaredeclaredinadifferentscope–theyarenotvisibletoeachother.

Page 100: C++ Programming in easy steps, 5th Edition
Page 101: C++ Programming in easy steps, 5th Edition

PassingargumentsFunctioncallsfrequentlysupplyargumentvaluestoafunction.Thesecanbeofanyquantityanddatatype,buttheymustagreewiththosespecifiedinthefunctionprototypedeclaration.

Notethatargumentspassedtoafunctiononlysupplyacopyoftheoriginalvalue,inaprocedureknownas“passingbyvalue”.

Thevaluespassedtoargumentscanbe“static”values,specifiedintheprogramcode,or“dynamic”valuesthatareinputbytheuser.Atacommandprompt,theC++cinfunctioncanbeusedwiththe>>inputstreamoperatortodirectavaluefromstandardinputtoavariable,likethis:

float num;cout <<“Pleaseenteranumber:”;cin>>num;

Functionprototypesmustbedeclaredbeforetheycanbedefined.Typically,theprototypesappearbeforethemainfunctionandtheirdefinitionsappearafterthemainfunction.

Inputcanthenbepassedtoafunctionasanargumentinafunctioncall,suchasworkWith(num).

Optionally,afunctionprototypecanassigndefaultvaluestoarguments,whichwillbeusedwhenacalldoesnotpassanargumentvalue.Multipleargumentscanbeassigneddefaultvaluesintheprototypebutthesemustalwaysappearattheendoftheargumentlist,afteranyotherarguments.

Inthesamewaythatfunctionscanbecalledfromthemainfunction,functionsmaycallotherfunctionsandpassarguments.

args.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Page 102: C++ Programming in easy steps, 5th Edition

Next,declareafunctionprototypethatreturnsafloatvalueandspecifiesasinglefloatargument,towhichadefaultvalueisassignedfloat fToC(float degreesF=32.0);

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Afterthemainfunction,definethe“fToC”functionwithstatementsthatwillreturnaconvertedvaluefloat fToC(float degreesF){

float degreesC=((5.0/9.0)*(degreesF-32.0));returndegreesC;

}

Inthemainfunction,insertastatementtodeclaretwofloat variables–tostoreaninputFahrenheittemperaturevalueanditsCentigradeequivalentfloat fahrenheit ,cent igrade;

Insertstatementstorequestthatuserinputbestoredinthefirstvariablecout <<“EnteraFahrenheit t emperature:\t ”;cin>>fahrenheit ;

Next,callthe“fToC”functiontoconverttheinputvalue–andassigntheconversiontothesecondvariablecent igrade=fToC(fahrenheit );

Now,outputamessagedescribingtheresultcout <<fahrenheit <<“Fis“<<cent igrade<<“C”;

Finally,addastatementtooutputafurthermessageusingthedefaultargumentvalueofthefunctionprototypecout <<endl<<“Freezingpoint :“<<fToC()<<“C”;

Save,compile,andruntheprogram,thenenteranumericvaluewhenrequestedtoseetheoutput

Page 103: C++ Programming in easy steps, 5th Edition

Inthesamewaythatfunctionscanbecalledfromthemainfunction,functionsmaycallotherfunctionsandpassargumentstothem.

Thenamesgiventotheargumentsandvariablesinthefunctiondefinitiondonotneedtobethesameasthevariablenamesinthecallingfunction–butithelpstoclarifytheprogram.

Page 104: C++ Programming in easy steps, 5th Edition
Page 105: C++ Programming in easy steps, 5th Edition

OverloadingfunctionsFunction“overloading”allowsfunctionsofthesamenametohappilyco-existinthesameprogram,providingtheirargumentsdifferinnumber,datatype,orbothnumberanddatatype.Thecompilermatchesafunctioncalltothecorrectversionofthefunctionbyrecognizingitsargumentnumberanddatatypes–aprocessknownas“functionresolution”.

Itisusefultocreateoverloadedfunctionswhenthetaskstheyaretoperformaresimilar,yetsubtlydifferent.

overload.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Belowthepreprocessorinstructions,declareafunctionprototypethatreturnsafloatvalueandhasoneargumentfloat computeArea(float );

Now,declaretwooverloadedfunctionprototypes–havingdifferentargumentstothefirstprototypefloat computeArea(float ,float );float computeArea(char,float ,float );

Belowtheprototypedeclarations,addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Afterthemainfunction,definethefirstfunctionthatreceivesjustoneargumentfloat computeArea(float diameter){

float radius=(diameter/2);return(3.141593*(radius*radius));

}

Page 106: C++ Programming in easy steps, 5th Edition

Functionsthatonlydifferbytheirreturndatatypecannotbeoverloaded–it’stheargumentsthatmustdiffer.Functionresolutiondoesnottakethereturndatatypesintoconsideration.

Belowthefirstfunctiondefinition,definetheoverloadedfunctionsthatreceivedifferentargumentsfloat computeArea(float width,float height ){

return(width*height );}float computeArea(charlet ter,float width,float height ){

return((width/2)*height );}

Inthemainfunction,insertstatementstodeclaretwovariables,andinitializeonewithuserinputfloat num,area;

cout <<“Enterdimensioninfeet :“;cin>>num;

Callthefirstfunctionandoutputitsreturnedvaluearea=computeArea(num);cout <<“Circle:Area=“<<area<<“sq.ft .”<<endl;

Calltheoverloadedfunctionsandoutputtheirreturnsarea=computeArea(num,num);cout <<“Square:Area=“<<area<<“sq.ft .”<<endl;area=computeArea(‘T ’,num,num);cout <<“Triangle:Area=“<<area<<“sq.ft .”<<endl;

Save,compile,andruntheprogram,thenenteranumericvaluewhenrequested,toseetheoutput

Page 107: C++ Programming in easy steps, 5th Edition

Thevaluepassedtothecharargumentisneverused–thatargumentisincludedmerelytodifferentiatethatoverloadedfunction.

Page 108: C++ Programming in easy steps, 5th Edition
Page 109: C++ Programming in easy steps, 5th Edition

OptimizingfunctionsFunctionscancallthemselvesrecursively,torepeatedlyexecutethestatementscontainedintheirfunctionbody–muchlikealoop.Aswithloops,arecursivefunctionmustcontainanincrementerandaconditionaltesttocallitselfagain,orstoprepeatingwhenaconditionismet.Thesyntaxofarecursivefunctionlookslikethis:

return-data-typefunction-name(argument-list){

statements-to-be-executed;incrementer;conditional-test-to-recall-or-exit;

}

Theincrementerwillchangethevalueofapassedargument–sosubsequentcallswillpasstheadjustedvaluebacktothefunction.

optimize.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Belowthepreprocessorinstructions,declaretwofunctionprototypesthatwillbothberecursivefunctionsint computeFactorials(int ,int );int factorial(int );

Belowtheprototypedeclarations,addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Afterthemainfunction,addthedefinitionforthefirstfunctionprototype–arecursivefunctionint computeFactorials(int num,int max){

cout <<“Factorialof“<<num<<“:”;cout <<factorial(num)<<endl;//Statements.num++;//Incrementer.if(num>max)return0;//Exit ...elsecomputeFactorials(num,max);//orcallagain.

Page 110: C++ Programming in easy steps, 5th Edition

}

Arecursivefunctiongenerallyusesmoresystemresourcesthanaloop–butitcanmakeformorereadablecode.

Definearecursivefunctionforthesecondprototypeint factorial(int n){

int result ;if(n==1)result =1;//Exit or...elseresult =(factorial(n-1)*n);//Decrement ..returnresult ;//andcallagain.

}

Atthestartofthemainfunction,insertacalltotherecursivefunctioncomputeFactorials(1,8);

Save,compile,andruntheprogramtoseetheoutput

Ifyouaccidentallyrunaninfiniterecursivefunction,presstheCtrl+Ckeystoterminatetheprocess.

Theoutputlistsfactorialvalues(factorial3is3x2x1=6,etc.),buttheprogramcanbeimprovedbyoptimizingthefactorial()function.Thisfunctiondoesnotneedavariableifwrittenwiththeternaryoperator.Itthencontainsjustonestatement,soitsdefinitioncanreplacetheprototypedeclarationasan“inline”declaration.Thismeansthattheprogramneednotkeepcheckingbetweenthedeclarationanddefinition,andsoimprovesefficiency.

Page 111: C++ Programming in easy steps, 5th Edition

Inlinedeclarationsmayonlycontainoneortwostatements,asthecompilerrecreatesthemateachcallingpoint–longerinlinedeclarationswould,therefore,produceamoreunwieldyprogram.

Deletethefactorial()functiondefinition,thenreplaceitsprototypedeclarationwiththisinlinedeclarationinlineint factorial(int n){return(n==1)?1:(factorial(n-1)*n);}

Save,compile,andruntheprogramagaintoseethesameoutput,producedmoreefficiently

Page 112: C++ Programming in easy steps, 5th Edition
Page 113: C++ Programming in easy steps, 5th Edition

Summary• AnifstatementevaluatesagiventestexpressionforaBooleanvalueoft rueorfalse.

• Statementscontainedinbracesafteranifstatementwillonlybeexecutedwhentheevaluationisfoundtobet rue.

• Theifandelsekeywordsareusedtoperformconditionalbranchingaccordingtotheresultofatestedexpression.

• Aswitchstatementisanalternativeformofconditionalbranchingthatmatchesacasestatementtoagivenvalue.

• Theforloopstructurehasparametersdeclaringaninitializer,atestexpression,andanincrementerordecrementer.

• Awhileloopanddo-whileloopmustalwayshaveanincrementerordecrementerwithintheirloopbody.

• Anytypeofloopcanbeimmediatelyterminatedbyincludingabreakstatementwithintheloopbody.

• Asingleiterationofanytypeofloopcanbeskippedbyincludingacont inuestatementwithintheloopbody.

• Functionsareusuallydeclaredasprototypesatthestartoftheprogram,anddefinedafterthemainfunction.

• Variablesdeclaredinafunctionareonlyaccessiblefromwithinthatfunction,astheyonlyhavelocalscope.

• Valuescanbepassedintofunctionsifargumentsaredeclaredinthefunctionprototypeanddefinition.

• Overloadedfunctionshavethesamenamebutadifferentnumberortypeofdeclaredarguments.

• Recursivefunctionsrepeatedlycallthemselvesuntilatestconditionismet.

• Shortfunctiondefinitionsofjustoneortwostatementscanbedeclaredinplaceofaprototypeusingtheinlinekeyword.

Page 114: C++ Programming in easy steps, 5th Edition

4

Handlingstrings

ThischapterdemonstrateshowtomanipulateC++textstringsasasimpler,morepowerfulalternativetocharacter

arrays.

CreatingstringvariablesGettingstringinputSolvingthestringproblemDiscoveringstringfeaturesJoining&comparingstringsCopying&swappingstringsFindingsubstringsReplacingsubstringsSummary

Page 115: C++ Programming in easy steps, 5th Edition
Page 116: C++ Programming in easy steps, 5th Edition

CreatingstringvariablesUnlikethechar,int ,float ,double,andbooldatatypes,thereisnonative“string”datatypeinC++–butits<st ring>libraryclassprovidesast ringobjectthatemulatesastringdatatype.Tomakethisavailabletoaprogram,thelibrarymustbeaddedwithan#include<st ring>directiveatthestartoftheprogram.

Likethe<iost ream>classlibrary,the<st ring>libraryispartofthestdnamespacethatisusedbytheC++standardlibraryclasses.Thismeansthatastringobjectcanbereferredtoasstd::st ring,ormoresimplyasst ringwhenausingnamespacestd;directiveisincludedatthestartoftheprogram.

Oncethe<st ring>libraryismadeavailable,ast ring“variable”canbedeclaredinthesamewayasothervariables.Thedeclarationmayoptionallyinitializethevariableusingthe=assignmentoperator,oritmaybeinitializedlaterintheprogram.

Additionally,ast ringvariablemaybeinitializedbyincludingatextstringbetweenparenthesesafterthevariablename.

TextstringsinC++mustalwaysbeenclosedwithin“”doublequotecharacters–‘’singlequotesareonlyusedtosurroundcharactervaluesofthechardatatype.

AC++st ringvariableismucheasiertoworkwiththanthechararrayswhichCprogrammersmustuse,asitautomaticallyresizestoaccommodatethelengthofanytextstring.Atalowerlevel,thetextisstillstoredasacharacterarray,butthest ringvariableletsyouignorethosedetails.Consequently,acharacterarraycanbeassignedtoast ringvariableusingthe=assignmentoperator.

Itisimportanttorememberthatwhennumericvaluesareassignedtoast ringvariable,theyarenolongeranumericdatatype,soarithmeticcannotbeperformedonthem.Forexample,attemptingtoaddst ringvaluesof“7”and“6”withthe+additionoperatorproducestheconcatenatedst ring“76”,notthenumericalvalueof13.Inthiscase,the+operatorrecognizesthatthecontextisnotarithmetical,soadoptstheguiseof“concatenationoperator”tounitethetwostrings.Similarly,the+=operatorappendsast ringtoanotherst ringandisusefultobuildlongstringsoftext.

Page 117: C++ Programming in easy steps, 5th Edition

Severalst ringvaluesarebuiltintoasinglelongstringintheexampleprogramdescribedbelow.

string.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingfourst ringvariabledeclarationsandafinalreturnstatementint main(){

st ringtext =“9”;st ringterm(“9“);st ringinfo=“Toys”;st ringcolor;//Addmorestatementshere.return0;

}

Inthemainfunction,afterthevariabledeclarationsinsertstatementstodeclareandinitializeacharacterarray,thenassignitsvaluetotheuninitializedst ringvariablecharhue[4]={‘R’,’e’,’d’,’\0’};color=hue;

Assignalongertextst ringtooneofthest ringvariablesinfo=“Balloons”;

Buildalongst ringbycombiningallthest ringvariablevaluesinthefirstst ringvariable,thenoutputthecombinedst ringvaluet ext +=(t erm+color+info);cout <<endl<<text <<endl;

Save,compile,andruntheprogramtoseetheoutput

Page 118: C++ Programming in easy steps, 5th Edition

Remembertoaddthespecial\0charactertomarktheendofastringinachararray.

Page 119: C++ Programming in easy steps, 5th Edition
Page 120: C++ Programming in easy steps, 5th Edition

GettingstringinputTheC++cinfunction,whichwasintroducedinthelastchaptertoinputnumericvalues,canalsoassigntextinputtost ringvariables.Thishasalimitation,asitcanonlybeusedtoinputasinglewordatatime–thecinfunctionstopsreadingtheinputwhenitencountersaspace,leavinganyothertextinthe“inputbuffer”.

Whenyouwanttoallowtheusertoinputastringwithspaces,suchasasentence,theget line()functioncanbeused.Thisfunctionrequirestwoargumentstospecifythesourceanddestinationofthestring.Forexample,wherethecinfunctionisthesource,andastringvariablenamed“str”isthedestination:

get line(cin,st r);

Theget line()functionreadsfromaninput“stream”untilitencountersa\nnewlinecharacterattheendoftheline–createdwhenyouhitReturn.

Caremustbetakenwhenmixingcinandget line()functions,astheget line()functionwillautomaticallyreadanythingleftontheinputbuffer–givingtheimpressionthattheprogramisskippinganinstruction.Thecin.ignore()functioncanbeusedtoovercomethisproblembyignoringcontentleftintheinputbuffer.

input.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingonestringvariabledeclarationandafinalreturnstatement

int main(){

st ringname;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementsassigningtheusernameinputtoastringvariable,thenoutputtingitsvaluecout <<“Pleaseenteryourfullname:”;cin>>name;cout <<“Welcome“<<name<<endl;

Page 121: C++ Programming in easy steps, 5th Edition

Next,insertastatementrequestingtheusernameagain,butthistimeassigningtheinputtothest ringvariablewiththeget linefunctionbeforeoutputtingitsvaluecout <<“Pleasere-enteryourfullname:”;get line(cin,name);cout <<“Thanks,“<<name<<endl;

Save,compile,andruntheprogramandenteryourfullnamewhenrequested

Thisunsatisfactoryresultshowsthatcinreadsuptothefirstspace,leavingthesecondnameintheinputbuffer,whichisthenreadbyget line()andsubsequentlyoutput.Theproblempersistsevenwhenyouenteronlyyourfirstname,becausecinleavesthenewlinecharacter,createdwhenyouhitReturn,ontheinputbuffer.

Edittheprogramtoresolvethisissuebyinsertingastatement,justbeforethecalltotheget linefunction,instructingittoignorecontentintheinputbuffercin.ignore(256,‘\n’);

Save,compile,andruntheprogramagain,thenre-enteryourfullnametoseetheprogramperformasrequired

Usethecinfunctionfornumericinputorsinglewordinput,butusethegetline()functionforstringinput.

Page 122: C++ Programming in easy steps, 5th Edition

Theargumentstothecin.ignore()functionspecifyitshoulddiscardupto256charactersandstopwhenitencountersanewlinecharacter.

Page 123: C++ Programming in easy steps, 5th Edition
Page 124: C++ Programming in easy steps, 5th Edition

SolvingthestringproblemAproblemariseswithst ringvariableswhenyouneedtoconvertthemtoadifferentdatatype,perhapstoperformarithmeticaloperationswiththosevalues.Asthest ringobjectisnotanativeC++datatypeast ringvariablevaluecannotbeconvertedtoanint oranyotherregulardatatypebycasting.

ThesolutionisprovidedbytheC++<sst ream>librarythatallowsast ringst reamobjecttoactasanintermediary,throughwhichst ringvaluescanbeconvertedtoanumericdatatype,andnumericvaluescanbeconvertedtoast ringdatatype.Tomakethisabilityavailabletoaprogram,thelibrarymustbeaddedwithan#include<sst ream>directiveatthestartoftheprogram.

Valuescanbeloadedintoast ringst reamobjectwiththefamiliaroutputstream<<operatorthatisusedwithcout statements.Contentscanthenbeextractedfromast ringst reamobjectwiththe>>inputstreamoperatorthatisusedwithcinstatements.

Inordertore-useast ringst reamobject,itmustfirstbereturnedtoitsoriginalstate.Thisrequiresitscontentstobesetasanemptyst ringanditsstatusbitflagstobecleared.

convert.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<sst ream>//Includest ringst reamsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringtwoinitializedvariablestobeconvertedint main(){

st ringterm=“100”;int number=100;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementstodeclareanintegervariable,st ringvariable,andast ringst reamobjectint num;//Tostoreaconvertedst ring.st ringtext ;//Tostoreaconvertedinteger.st ringst reamst ream;//Toperformconversions.

Page 125: C++ Programming in easy steps, 5th Edition

Next,usethestreamoutputoperatortoloadtheinitializedst ringvalueintothest ringst reamobjectst ream<<term;//Loadthest ring.

Usethestreaminputoperatortoextractcontentfromthest ringst reamobjectintotheuninitializedintegervariablest ream>>num;//Ext ract theinteger.

Performarithmeticontheintegerandoutputtheresultnum/=4;cout <<“Integervalue:”<<num<<endl;

Resetthest ringst reamobjectreadyforre-usest ream.st r(“”);//Emptythecontents.st ream.clear();//Emptythebit flags.

Now,usethestreamoutputoperatortoloadtheinitializedintegervalueintothest ringst reamobjectst ream<<number;//Loadtheinteger.

Usethestreaminputoperatortoextractcontentfromthest ringst reamobjectintotheuninitializedst ringvariablest ream>>text ;//Ext ract thest ring.

Performconcatenationonthest ringandoutputtheresultt ext +=“PerCent”;cout <<“St ringvalue:”<<text <<endl;

Save,compile,andruntheprogramtoseetheconvertedoutputvalues

Noticehowthestringstreamobject’sstr()functionisusedheretoresetitscontentstoanemptystring.

Page 126: C++ Programming in easy steps, 5th Edition

Anon-emptystringstreamobjecthasbitflagsindicatingitsstatusasgood,bad,eof,orfail–theseshouldbeclearedbeforere-usebythestringstreamobject’sclear()function,asdemonstratedhere.

Page 127: C++ Programming in easy steps, 5th Edition
Page 128: C++ Programming in easy steps, 5th Edition

DiscoveringstringfeaturesTheC++<st ring>libraryprovidesanumberoffunctionsthatmakeiteasytoworkwithstrings.Tousethem,simplyaddthefunctionnameafterthest ringvariablenameandadot.Forexample,withast ringst reamvariablenamed“msg”youcancalluponthesize()function,toreturnitscharacterlength,withmsg.size().

Ast ringvariablecanbeemptiedofallcharactersbyassigningitanemptystringwithtwodoublequoteswithoutspacing–as“”,oralternativelybycallingthe<st ring>library’sclear()function.

Unlikeachararray,ast ringvariablewilldynamicallyenlargetoaccommodatethenumberofcharactersassignedtoit,anditscurrentmemorysizecanberevealedwiththe<st ring>library’scapacity()function.Onceenlarged,theallocatedmemorysizeremains,evenwhenasmallerst ringgetsassignedtothevariable.

Thelength()functioncanbeusedinplaceofthesize()functiontorevealthesizeofastringvalue.

The<st ring>library’sempty()functionreturnsaBooleant rue(1)orfalse(0)responsetorevealwhetherthestringisemptyornot.

features.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<iost ream>usingnamespacestd;

Belowthepreprocessordirectives,declareafunctionprototypewithasinglest ringdatatypeargumentvoidcomputeFeatures(st ring);

Addamainfunctioncontainingafinalreturnstatementanddeclaringaninitializedst ringvariableint main()

Page 129: C++ Programming in easy steps, 5th Edition

{st ringtext =“C++isfun”;//Addmorestatementshere.return0;

}

Afterthemainfunction,definethedeclaredfunctiontodisplaythest ringvariablevaluewhencalledvoidcomputeFeatures(st ringtext ){

cout <<endl<<“St ring:”<<text <<endl;}

Inthefunctiondefinition,addstatementstooutputfeaturesofthest ringvariablecout <<“Size:”<<text .size();cout <<“Capacity:”<<text .capacity();cout <<“Empty?:”<<text .empty()<<endl;

Inthemainfunction,insertacalltothedefinedfunctioncomputeFeatures(text );

Next,inthemainfunction,insertastatementtoenlargethest ringvalueandcallthefunctiontoseeitsfeaturest ext +=“foreveryone”;computeFeatures(text );

Now,insertastatementtoreducethest ringvaluet ext =“C++Fun”;computeFeatures(text );

Finally,insertastatementtoemptythest ringvariablet ext .clear();computeFeatures(text );

Save,compile,andruntheprogramtoseetheoutput

Page 130: C++ Programming in easy steps, 5th Edition

Theempty()functionisusefultocheckiftheuserhasenteredrequestedinput.

Aspaceoccupiesonememoryelement–justlikeacharacterdoes.

Page 131: C++ Programming in easy steps, 5th Edition
Page 132: C++ Programming in easy steps, 5th Edition

Joining&comparingstringsWhenthe+operatorisusedtoconcatenatestringsinanassignment,thecombinedstringsgetstoredinthest ringvariable.Butwhenitisusedwiththecout function,thestringsareonlycombinedintheoutput–thevariablevaluesareunchanged.

The<st ring>library’sappend()functioncanalsobeusedtoconcatenatestrings,specifyingthest ringvaluetoappendasanargumentwithinitsparentheses.Whenthisisusedwiththecoutfunction,thestringsarecombinedinthevariable,thenitsvaluewrittenasoutput–inthiscase,thevariablevaluedoeschange.

Stringcomparisonscanbemade,inthesamewayasnumericcomparisons,withthe==equalityoperator.Thisreturnst rue(1)whenbothstringspreciselymatch,otherwiseitreturnsfalse(0).

Alternatively,the<st ring>library’scompare()functioncanbeusedtocompareast ringvaluespecifiedasitsargument.Unlikethe==equalitycomparison,thecompare()functionreturnszerowhenthestringsareidentical,byexaminingthest ringvalue’scombinedASCIIcodevalues.Whenthest ringargumenttotalsmorethanthefirststring,itreturns-1,otherwiseitreturns1.

compare.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringthreeinitializedst ringvariablesint main(){

st ringlang=“C++”;st ringterm=“Programming”;st ringtext =“C++Programming”;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementstooutputtwost ringvaluescombinedwiththe+concatenateoperatorandthe(unchanged)valueofthefirstvariablecout <<“Concatenated:”<<(lang+term)<<endl;cout <<“Original:”<<lang<<endl;

Page 133: C++ Programming in easy steps, 5th Edition

Next,insertstatementstooutputtwost ringvaluescombinedwiththeappend()functionandthe(changed)valueofthefirstvariablecout <<“Appended:”<<lang.append(term)<<endl;cout <<“Original:”<<lang<<endl<<endl;

Usethe==equalityoperatortocomparetwost ringvaluesthatdiffer,thentwost ringvaluesthatmatchcout <<“Differ:”<<(lang==term)<<endl;cout <<“Match:”<<(lang==text )<<endl<<endl;

Now,usethecompare()functiontocomparethreest ringvalues,examiningtheirASCIIcodetotalvaluescout <<“Match:”<<lang.compare(text )<<endl;cout <<“Differ:”<<lang.compare(term)<<endl;cout <<“LowerASCII:”<<lang.compare(“zzzzz”)<<endl;

Save,compile,andruntheprogramtoseetheoutput

The+=assignmentoperatorcanalsobeusedtoappendastring.

Incomparisons,characterorderistakenintoaccount–socomparing“za”to“az”revealsthat“za”hasagreatertotal.IntermsofASCIIvalues,‘a’is97,and‘z’is122.

Page 134: C++ Programming in easy steps, 5th Edition
Page 135: C++ Programming in easy steps, 5th Edition

Copying&swappingstringsStringvaluescanbeassignedtoast ringvariablebythe=assignmentoperator,orbythe<st ring>library’sassign()function.Thisfunctionspecifiesthest ringvaluetobecopiedtothevariableasanargumentwithinitsparentheses.

Optionally,theassign()functioncancopyjustapartofthespecifiedst ringvaluebystatingthepositionofthestartingcharacterasasecondargument,andthenumberofcharacterstocopyasathirdargument.

Thecontentsofast ringvariablecanbeexchangedforthatofanotherst ringvariablebythe<st ring>library’sswap()function.Inthiscase,thecontentsofthefirstvariablereceivesthoseofthesecondvariable,whichinturnreceivesthoseofthefirstvariable.

swap.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringthreest ringvariables–withoneinitializedint main(){

st ringfront ;st ringback;st ringtext =“Alwayslaughwhenyoucan.It \’scheapmedicine.”;//Addmorestatementshere.return0;

}

Inthemainfunction,insertastatementtoassigntheentirevalueoftheinitializedst ringvariabletothefirstuninitializedst ringvariablefront .assign(text );

Next,insertastatementtooutputthenewlyassignedstringvaluecout <<endl<<“Front :”<<front <<endl;

Now,insertastatementtoassignonlythefirst27charactersoftheinitializedvariabletothefirstvariablefront .assign(text ,0,27);

Page 136: C++ Programming in easy steps, 5th Edition

Outputthenewlyassignedst ringvaluecout <<endl<<“Front :”<<front <<endl;

Next,assignonlythelastpartoftheinitializedst ringvariabletotheseconduninitializedvariable,startingatcharacter(element)27back.assign(t ext ,27,t ext .size());

Now,outputthisnewlyassignedst ringvaluecout <<“Back:”<<back<<endl;

Finally,exchangetheassignedst ringvaluescontainedinthefirstandsecondst ringvariables,thenoutputtheexchangedvaluesback.swap(front );cout <<endl<<“Front :”<<front <<endl;cout <<“Back:”<<back<<endl;

Save,compile,andruntheprogramtoseetheoutput

Usethe=assignmentoperatortoassigncompletestringsandtheassign()functiontoassignpartialstrings.

Usetheswap()functionwhereverpossible,ratherthancreatingadditionalstringvariables.

Page 137: C++ Programming in easy steps, 5th Edition
Page 138: C++ Programming in easy steps, 5th Edition

FindingsubstringsAst ringvaluecanbesearchedtoseeifitcontainsaspecified“substring”usingthefind()functionofthe<st ring>library.Itsparenthesesshouldspecifythesubstringtoseekasitsfirstargument,andtheindexnumberofthecharacteratwhichtostartsearchingasitssecondargument.

Whenasearchsuccessfullylocatesthespecifiedsubstring,thefind()functionreturnstheindexnumberofthefirstoccurrenceofthesubstring’sfirstcharacterwithinthesearchedstring.Whenthesearchfails,find()returnsavalueof-1toindicatefailure.

Thereareseveralotherfunctionsinthe<st ring>librarythatarerelatedtothefind()function.Twoofthesearethefind_first_of()functionandthefind_first_not_of()function.Insteadofseekingthefirstoccurrenceofacompletest ring,asfind()does,thefind_first_of()functionseeksthefirstoccurrenceofanyofthecharactersinaspecifiedst ring,andfind_first_not_of()seeksthefirstoccurrenceofacharacterthatisnotinthespecifiedst ring.

Thefind_last_of()andfind_last_not_of()functionsworkinasimilarmanner–butbeginsearchingattheendofthest ringthenmoveforwards.

find.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatement,aninitializedstringvariabledeclaration,anddeclaringanintegervariabletostoresearchresultsint main(){

st ringtext =“Icanresist anythingbut temptat ion.”;int num;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementstooutputthestartpositionofasubstringwithintheentirest ringvariablenum=text .find(“resist”,0);cout <<“Posit ion:”<<num<<endl;

Next,insertastatementtoseekanon-existentsubstringwithintheentirest ringvariable

Page 139: C++ Programming in easy steps, 5th Edition

andoutputtheresultnum=text .find(“nonsuch”,0);cout <<“Result :”<<num<<endl;

Now,insertastatementtooutputthestartpositionofthefirstoccurrenceanycharactersofan“If”substringfoundwithintheentirest ringvariablenum=text .find_first_of(“If”);cout <<“First I:”<<num<<endl;

Insertastatementtoreportthestringpositionofthefirstcharacternotwithinthe“If”substringnum=text .find_first_not_of(“If”);cout <<“First not I:”<<num<<endl;

Next,insertastatementtoseekthelastoccurrenceoftheletter“t”withinthest ringvariableandoutputitspositionnum=text .find_last_of(“t ”);cout <<“Last t :”<<num<<endl;

Now,addastatementtoreportthest ringpositionofthelastcharacterwithinthest ringvariablethatisnota“t”num=text .find_last_not_of(“t ”);cout <<“Last not t :”<<num<<endl;

Save,compile,andruntheprogramtoseethesearchresultsindicatingfailureorthepositionswhenlocated

Thesearchesarecasesensitive,soseeking“If”and“if”mayproducedifferentresults–here,uppercase‘I’matches.

Page 140: C++ Programming in easy steps, 5th Edition

Thefirstcharacterinastringisatpositionzero,notatpositionone.

Page 141: C++ Programming in easy steps, 5th Edition
Page 142: C++ Programming in easy steps, 5th Edition

ReplacingsubstringsThe<st ring>librarycontainsanumberofusefulfunctionstomanipulatesubstrings.Ast ringcanbeinsertedintoanotherst ringusingtheinsert ()function.Thisrequirestheindexpositionatwhichthest ringshouldbeinsertedasitsfirstargument,andthest ringvaluetobeinsertedasitssecondargument.

Conversely,asubstringcanberemovedfromast ringusingtheerase()function.Thisrequirestheindexpositionatwhichitshouldbeginerasingasitsfirstargument,andthenumberofcharacterstobeerasedasitssecondargument.

Thereplace()functionneatlycombinestheerase()andinsert ()functionstobothremoveasubstringandinsertareplacement.Itrequiresthreeargumentsspecifyingthepositionatwhichitshouldbeginerasing,thenumberofcharacterstobeerased,andthereplacementst ringtobeinsertedatthatposition.

Asubstringcanbecopiedfromast ringusingthesubst r()function,statingtheindexpositionatwhichitshouldbegincopyingasitsfirstargument,andthenumberofcharacterstobecopiedasitssecondargument.

Thecharacteratanyspecifiedpositionwithinast ringcanbecopiedusingtheat ()function,whichrequirestheindexpositionasitsargument.Thefinalcharacterinast ringalwayshasanelementindexnumberonelessthanthelengthofthest ring–becauseindexnumberingstartsatzero,notone.

sub.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatement,aninitializedst ringvariabledeclaration,andastatementoutputtingthest ringvariablevalueint main(){

st ringtext =“Idoliketheseaside”;cout <<“Original:”<<text <<endl;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementstoinsertasubstringintothevariablevalueat

Page 143: C++ Programming in easy steps, 5th Edition

indexposition10,andtooutputthemodifiedst ringtext .insert (10,“tobebeside“);cout <<“Inserted:”<<text <<endl;

Next,insertstatementstoerasetwocharactersfromthemodifiedst ringvaluestartingatindexpositionthree,andtooutputtherevisedst ringtext .erase(2,3);cout <<“Erased:”<<text <<endl;

Now,insertstatementstoremove25charactersatindexpositionseven,insertareplacementsubstring,thenoutputtherevisedst ringagaint ext .replace(7,25,“st rollingbythesea”);cout <<“Replaced:”<<text <<endl;

Finally,insertstatementstooutputninecopiedcharactersatindexpositionseven,andtooutputthefinalcharacterinthestringcout <<“Copied:”<<text .subst r(7,9)<<endl;cout <<“Last character:”<<t ext .at (t ext .size()-1)<<endl;

Save,compile,andruntheprogramtoseetheoutputshowinghowthest ringhasbeenmanipulated

Theinsert()functioncanoptionallyhaveathirdandfourthargument–specifyingthepositioninthesubstringatwhichtobegincopying,andthenumberofcharacterstobecopied.

Thereplace()functioncanoptionallyhaveafourthandfifthargument–specifying

Page 144: C++ Programming in easy steps, 5th Edition

thepositioninthesubstringatwhichtobegincopying,andthenumberofcharacterstobecopied.

Page 145: C++ Programming in easy steps, 5th Edition
Page 146: C++ Programming in easy steps, 5th Edition

Summary• TheC++<st ring>libraryprovidesa“string”objectthatemulatesadatatype–sothatst ring

variablescanbecreated.

• Arithmeticcannotbeperformedonnumericvaluesassignedtost ringvariablesuntiltheyareconvertedtoanumericdatatype.

• Thestandardcinfunctionreadsfromstandardinputuntilitencountersaspace,socanbeusedtoinputasingleword,andprovidesanignore()functiontodisregardtheinputbuffer.

• Theget line()functionreadsfromstandardinputuntilitencountersanewline,socanbeusedtoinputastringoftext.

• TheC++<sst ream>libraryprovidesa“stringstream”objectthatactsanintermediarytoconvertstringstootherdatatypes.

• Ast ringvariablecanbeemptiedbyassigningitanemptystring(=“”)orbycallingitsclear()function.

• Featuresofast ringvariablecanberevealedbycallingitssize(),capacity(),andempty()functions.

• Multiplest ringvaluescanbeconcatenatedbythe+operator.

• Ast ringcanbeappendedtoanotherst ringbythe+=operatororbycallingitsappend()function.

• Ast ringcanbecomparedtoanotherst ringbythe==operatororbycallingitscompare()function.

• Ast ringvaluecanbeassignedtoast ringvariableusingthe=operatororbycallingitsassign()function.

• Theswap()functionswapsthevaluesoftwost ringvariables.

• Substringsofast ringcanbesoughtwiththefind()function,orspecializedfunctionssuchasfind_first_of(),andacharacterretrievedfromaspecifiedindexpositionbytheat ()function.

• Asubstringcanbeaddedtoast ringbyitsinsert ()function,removedbyitserase()function,replacedbyitsreplace()function,orcopiedbyitssubst r()function.

Page 147: C++ Programming in easy steps, 5th Edition

5

Readingandwritingfiles

Thischapterdemonstrateshowtostoreandretrievedataintextfiles,andillustrateshowtoavoiderrorsinC++

programs.

WritingafileAppendingtoafileReadingcharacters&linesFormattingwithgetlineManipulatinginput&outputPredictingproblemsRecognizingexceptionsHandlingerrorsSummary

Page 148: C++ Programming in easy steps, 5th Edition
Page 149: C++ Programming in easy steps, 5th Edition

WritingafileTheabilitytoreadandwritefilesfromaprogramprovidesausefulmethodofmaintainingdataonthecomputer ’sharddisk.Theformatofthedatamaybespecifiedashuman-readableplaintextformatormachine-readablebinaryformat.

ThestandardC++<fst ream>libraryprovidesfunctionsforworkingwithfiles,whichcanbemadeavailablebyaddingan#include<fst ream>directiveatthestartoftheprogram.

Foreachfilethatistobeopened,afilestreamobjectmustfirstbecreated.Thiswillbeeitheran“ofstream”(outputfilestream)object,forwritingdatatothefile,oran“ifstream”(inputfilestream)object,forreadingdatafromthefile.Theofst reamobjectisusedlikethecoutfunctionthatwritestostandardoutput,andtheifst reamobjectworkslikethecinfunctionthatreadsfromstandardinput.

Thedeclarationofafilestreamobjectforwritingoutputbeginswiththeofst reamkeyword,thenachosennameforthatparticularfilestreamobjectfollowedbyparenthesesnominatingthetextfiletowriteto.So,thedeclarationsyntaxlookslikethis:

ofst reamobject-name(“file-name”);

Theargumentnominatingthetextfilemayoptionallycontainthefullfilepath,suchas“C:\data\log.txt”or“/home/user/log.txt”,otherwisetheprogramwillseekthefilewithinthedirectoryinwhichtheprogramresides.

Beforewritingoutputtoafile,theprogramshouldalwaysfirsttestthatthefilestreamobjecthasactuallybeencreated.Typically,thisisperformedbyanifstatementthatallowstheprogramtowriteoutputonlywhenthetestissuccessful.

Ifanominatedfilealreadyexists,itwillbydefaultbeoverwrittenwithoutwarning.Otherwise,anewfilewillbecreatedandwritten.

Thenominatedfilenameorpathmustbeenclosedwithindoublequotes,likeastring.

Afterwritingoutputtoanominatedfile,theprogramshouldalwayscalltheassociatedfilestreamobject’sclose()functiontoclosetheoutputfilestream.

Theprogramdescribedbelowfirstbuildsastringforwritingasoutput.Thisiswrittentoanominatedfilewhenthefilestreamobjecthasbeensuccessfullycreated,thenthefilestreamclosed.

Page 150: C++ Programming in easy steps, 5th Edition

write.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<fst ream>//Includefilest reamsupport .# include<st ring>#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementandbuildingalengthytextstringinast ringvariableint main(){

st ringpoem=“\n\t Ineversawamanwholooked”;poem.append(“\n\tWithsuchawist fuleye”);poem.append(“\n\tUponthat lit t letent ofblue”);poem.append(“\n\tWhichprisonerscallthesky”);//Addmorestatementshere.return0;

}

Inthemainfunction,createanoutputfilestreamobjectofst reamwriter(“poem.txt”);

Insertstatementstowritethest ringtoafileorexit,thensave,compile,andruntheprogramtoseetheresultif(!writer){

cout <<“Erroropeningfileforoutput”<<endl;return-1;//Signalanerrorthenexit theprogram.

}writer<<poem<<endl;//Writeoutput .writer.close();//Closefilest ream.

Page 151: C++ Programming in easy steps, 5th Edition

Stringvaluescancontain\nnewlineand\ttabescapesequencesforformattinglines.

Noticehowthenewlineandtabcharactersarepreservedinthetextfile.

Page 152: C++ Programming in easy steps, 5th Edition
Page 153: C++ Programming in easy steps, 5th Edition

AppendingtoafileWhenafilestreamobjectiscreated,theparenthesesfollowingitschosennamecanoptionallycontainadditionalarguments,specifyingarangeoffile“modes”tocontrolthebehaviorofthatfilestreamobject.Thesefilemodesarepartoftheiosnamespace,somustbeexplicitlyaddressedusingthatprefix.Eachfilemodeislistedinthetablebelow,togetherwithabehaviordescription:

Mode: Behavior:

ios::out Openafiletowriteoutput

ios::in Openafiletoreadinput

ios::app Openafiletoappendoutputattheendofanyexistingcontent

ios::t runc Truncatetheexistingfile(defaultbehavior)

ios::ate Openafilewithouttruncatingandallowdatatobewrittenanywhereinthefile

ios::binary Treatthefileasbinaryformatratherthantextsothedatamaybestoredinnon-textformat

Thepreprocessordirectiveusingnamespacestd;allowsthestdnamespaceprefixtobeomitted–socoutreferstothestd::coutfunction.Theiosnamespaceexistswithinthestdnamespace–sothefilemodescanbeexplicitlyaddressedusingbothnamespaceprefixes,forexamplestd::ios::out.

Multiplemodesmaybespecifiediftheyareseparatedbya“|”pipecharacter.Forexample,thesyntaxofastatementtoopenafileforbinaryoutputlookslikethis:

ofst reamobject-name(“file-name”,ios::out |ios::binary);

Thedefaultbehaviorwhennomodesareexplicitlyspecifiedregardsthefileasatextfilethatwillbetruncatedafterwriting.

Themostcommonlyspecifiedmodeisios::app,whichensuresexistingcontentwillbeappended,ratherthanoverwritten,whennewoutputiswrittentothenominatedfile.

Theprogramdescribedbelowappendsdatatothetextfilecreatedinthepreviousexample.

Page 154: C++ Programming in easy steps, 5th Edition

append.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<fst ream>//Includefilest reamsupport .# include<st ring>#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementandbuildingatextstringinast ringvariableint main(){

st ringinfo=“\n\tTheBalladofReadingGaol”;info.append(“\n\t \t \tOscarWilde1898”);//Addmorestatementshere.return0;

}

Inthemainfunction,createanoutputfilestreamobject–specifyingafilemodethatwillappendtoexistingtextofst reamwriter(“poem.txt”,ios::app);

Insertstatementstoappendthest ringtoafileorexit,thensave,compile,andruntheprogramtoseetheresultif(!writer){

cout <<“Erroropeningfileforoutput”<<endl;return-1;//Signalanerrorthenexit theprogram.

}writer<<info<<endl;//Appendoutput .writer.close();//Closefilest ream.

Page 155: C++ Programming in easy steps, 5th Edition

Thefilemustallowtheprogramsuitablereadandwritepermissions.

Page 156: C++ Programming in easy steps, 5th Edition
Page 157: C++ Programming in easy steps, 5th Edition

Readingcharacters&linesTheifst reamfilestreamobjecthasaget ()functionthatcanbeusedinalooptoreadafileandassigneachcharacterinturntothecharvariablespecifiedasitsargument:

read.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<fst ream>//Includefilest reamsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementandtwovariabledeclarations–onevariabletostoreacharacterandanothertocountloopiterationsint main(){

charlet ter;int i;//Addmorestatementshere.return0;

}

Inthemainfunction,createaninputfilestreamobjecttoreadthetextfilefromthepreviousexampleifst reamreader(“poem.txt”);

Insertstatementstoexitunlessthefilestreamobjectexistsif(!reader){

cout <<“Erroropeninginput file”<<endl;return-1;//Signalanerrorthenexit theprogram.

}

Next,insertalooptoreadthetextfile,assigningeachcharacterinturntothevariableandoutputtingitsvalueelsefor(i=0;!reader.eof();i++){

reader.get (let ter);cout <<let ter;

}

Finally,insertstatementstoclosethefilestreamandoutputthetotalnumberofloopiterationsreader.close();

Page 158: C++ Programming in easy steps, 5th Edition

cout <<“Iterat ions:”<<i<<endl;

Noticehowtheifstreameof()functionisusedtocheckifthe“endoffile”hasbeenreached.

Save,compile,andruntheprogramtoseethetextfilecontentsandloopcountgetdisplayedonstandardoutput

Thisprogramworkswellenoughbuttheloopmustmakemanyiterationstooutputthetextfilecontents.Efficiencycouldbeimprovedbyreadingalineoneachiterationoftheloop:

InsertapreprocessordirectivetomaketheC++stringlibraryavailabletotheprogram#include<st ring>

Replacethecharvariabledeclarationwithast ringvariabledeclarationst ringline;

Replacebothstatementsintheforlooptoreadlines,thensave,compile,andruntheprogramoncemoreget line(reader,line);cout <<line<<endl;

Page 159: C++ Programming in easy steps, 5th Edition

Outputanendlaftereachlineoutput–becausegetline()stopsreadingwhenitmeetsa\nnewlinecharacter.

Page 160: C++ Programming in easy steps, 5th Edition
Page 161: C++ Programming in easy steps, 5th Edition

FormattingwithgetlineTheget line()functioncanoptionallyhaveathirdargumenttospecifyadelimiteratwhichtostopreadingaline.Thiscanbeusedtoseparatetextreadfromatabulatedlistinadatafile:

format.cpp

Inaplaintexteditor,createatextfilecontaining12itemsofdataoffouritemsperline,eachseparatedbyatab

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<fst ream>//Includefilest reamsupport .# include<st ring>#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementandfourvariabledeclarations–afixednumber,ast ringarraytostoredata,andtwocountervariablessettozero

int main(){

const int RANGE=12;st ringtab[RANGE];int i=0,j=0;//Addmorestatementshere.return0;

}

Insertastatementtocreateaninputfilestreamobjectifst reamreader(“records.txt”);

Insertstatementstoexitunlessthefilestreamobjectexistsif(!reader){

cout <<“Erroropeninginput file”<<endl;return-1;

}

Page 162: C++ Programming in easy steps, 5th Edition

Thestringarraymusthaveasufficientnumberofelementstostoreeachitemofdata–itwouldneedtobeenlargedtohandlemorerecords.

Next,insertaloopthatwillreadeachlineintothest ringarray–readinguptoa\t tabforthefirstthreeitemsanduptoa\nnewlineforthefourthitemoneachlinewhile(!reader.eof()){

if((i+1)%4==0)get line(reader,t ab[i++],‘\n’);

elseget line(reader,t ab[i++],‘\t ’);

}

Now,closethefilestreamandresetthecounterreader.close();i=0;

Insertasecondlooptooutputthedatastoredineacharrayelement,formattedwithdescriptionsandnewlineswhile(i<RANGE){

cout <<endl<<“RecordNumber:”<<++j<<endl;cout <<“Forename:”<<tab[i++]<<endl;cout <<“Surname:”<<tab[i++]<<endl;cout <<“Department :”<<tab[i++]<<endl;cout <<“Telephone:”<<tab[i++]<<endl;

}

Save,compile,andruntheprogramtoseetheformattedoutputfromthetextfile

Page 163: C++ Programming in easy steps, 5th Edition

Theifstatementtestsiftheitemnumber(elementnumberplus1)isexactlydivisiblebyfour,todeterminewhethertoreaduptoanewlineortabcharacter.

Therecordcountermustuseaprefixincrementertoincreasethevariablevaluebeforeitisoutput.

Page 164: C++ Programming in easy steps, 5th Edition
Page 165: C++ Programming in easy steps, 5th Edition

Manipulatinginput&outputThebehaviorofinputandoutputstreamscanbemodifiedusing“insertionoperators”withthecout andcinfunctions.Specifyinganintegerargumenttotheirwidth()functionsetsthestreamcharacterwidth.Wherethecontentdoesnotfilltheentirestreamwidth,afillcharactermaybespecifiedastheargumenttotheirfill()functiontoindicatetheemptyportion.Similarly,thedefaultprecisionofsixdecimalplacesforfloatingpointnumberscanbechangedbyspecifyinganintegertotheirprecision()function.Statementsusinginsertionoperatorstomodifyastreamshouldbemadebeforethoseusingthe<<or>>operators.

Insertionoperatorsmodifyjustonestreamobject–subsequentstreamobjectsusethedefaults,unlesstheytoogetmodifiedfirstbyinsertionoperators.

The<iost ream>libraryprovidesthe“manipulators”listedinthetablebelow,whichmodifyastreamusingthe<<or>>operators.

Manipulator: Display:

noboolalpha* Booleanvaluesas1or0

boolalpha Booleanvaluesas“true”or“false”

dec* Integersasbase10(decimal)

hex Integersasbase16(hexadecimal)

oct Integersasbase8(octal)

right * Textright-justifiedintheoutputwidth

left Textleft-justifiedintheoutputwidth

internal Signleft-justified,numberright-justified

noshowbase* Noprefixindicatingnumericbase

showbase Prefixindicatingnumericbase

noshowpoint * Wholenumberonlywhenafractioniszero

showpoint Decimalpointforallfloatingpointnumbers

noshowpos* No+prefixbeforepositivenumbers

showpos Prefixpositivenumberswitha+sign

Page 166: C++ Programming in easy steps, 5th Edition

noskipws* Donotskipwhitespacefor>>input

skipws Skipwhitespacefor>>input

fixed* Floatingpointnumberstosixdecimalplaces

scient ific Floatingpointnumbersinscientificnotation

nouppercase* Scientificaseandhexadecimalnumberasff

uppercase ScientificasEandhexadecimalnumberasFF

Manipulatorsmarkedwithan*arethedefaultbehaviors.

manipulate.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringtwoinitializedvariablesint main(){

boolisTrue=1;int num=255;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementstosetthewidthandfillofanoutputstream,thenoutputatextstringonitcout .width(40);cout .fill(‘.’);cout <<“Output”<<endl;

Next,insertstatementstosettheprecisionofanoutputstreamtostoptruncationofdecimalplaces–thenoutputafloatingpointnumbershowingallitsdecimalplaces

cout .precision(11);cout <<“Pi:”<<3.1415926536<<endl;

Now,insertstatementsthatusemanipulatorstooutputthevariablevaluesinmodified

Page 167: C++ Programming in easy steps, 5th Edition

formatscout <<isTrue<<“:”<<boolalpha<<isTrue<<endl;cout <<num<<“:”<<hex<<showbase<<uppercase<<num<<endl;

Save,compile,andruntheprogramtoseetheoutput

Manipulatorsaffectallinputoroutputonthatstream.Forexample,theboolalphamanipulatorwilldisplayallBooleanvaluesonthatstreaminwrittenform.

Page 168: C++ Programming in easy steps, 5th Edition
Page 169: C++ Programming in easy steps, 5th Edition

PredictingproblemsDespitethebesteffortsoftheprogrammer,C++programsmayunfortunatelycontainone,ormore,ofthesethreetypesofbugs:

• Syntaxerrors–thecodecontainsincorrectuseoftheC++language.Forexample,anopeningbracedoesnothaveamatchingclosingbrace.

• Logicerrors–thecodeissyntacticallycorrect,butattemptstoperformanoperationthatisillegal.Forexample,theprogrammayattempttodivideanumberbyzero,causinganerror.

• Exceptionerrors–theprogramrunsasexpecteduntilanexceptionalconditionisencounteredthatcrashestheprogram.Forexample,theprogrammayrequestanumber,whichtheuserentersinwordformratherthaninnumericform.

TheC++standardsallowthecompilertospot“compile-time”errorsinvolvingsyntaxandlogic,butthepossibilityofexceptionalerrorsismoredifficulttolocateastheyonlyoccurat“run-time”.Thismeansthattheprogrammermusttrytopredictproblemsthatmayariseandpreparetohandlethoseexceptionalerrors.

Thefirststepistoidentifywhichpartoftheprogramcodethatmay,undercertainconditions,causeanexceptionerror.Thiscanthenbesurroundedbya“try”block,whichusesthet rykeywordandenclosesthesuspectcodewithinapairofbraces.

Alwaysconsiderthattheuserwillperformtheunexpected–thenensureyourprogramscanhandlethoseactions.

Whenanexceptionerroroccurs,thet ryblockthen“throws”theexceptionouttoa“catch”block,whichimmediatelyfollowsthet ryblock.Thisusesthecatchkeywordandenclosesstatementstohandletheexceptionerrorwithinapairofbraces.

Theprogramdescribedbelowhasat ryblockcontainingaloopthatincrementsaninteger.Whentheintegerreachesfive,athrow()functionmanuallythrowsanexceptiontothecatchblockexceptionhandler,passingtheintegerargument.

Page 170: C++ Programming in easy steps, 5th Edition

try.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringanintegervariableforincrementbyaloopint main(){

int number;//Addmorestatementshere.return0;

}

Inthemainfunction,insertt ryandcatchblockstohandlea“badnumber”exceptiont ry{}catch(int num){}

Inthet ryblock,insertalooptoincrementthevariablefor(number=1;number<21;number++){

if(number>4)throw(number);elsecout <<“Number:”<<number<<endl;

}

Inthecatchblock,insertanexceptionhandlerstatementcout <<“Except ionat :”<<num<<endl;

Save,compile,andruntheprogramtoseethethrownexceptiongetcaughtbythecatchblock

Page 171: C++ Programming in easy steps, 5th Edition

Whenanexceptionoccurs,controlpassestothecatchblock–inthisexample,theloopdoesnotcomplete.

Page 172: C++ Programming in easy steps, 5th Edition
Page 173: C++ Programming in easy steps, 5th Edition

RecognizingexceptionsWhenaprogramexceptionoccurswithinat ryblock,an“exception”objectisautomaticallythrown.Areferencetotheexceptioncanbepassedtotheassociatedcatchblockintheparenthesesafterthecatchkeyword.Thisspecifiestheargumenttobeanexcept iontype,andachosenexceptionnameprefixedbythe&referenceoperator.Forexample,except ion&error.

Moreonreferencesinthenextchapter.

Onceanexceptionreferenceispassedtoacatchblock,anerrordescriptioncanberetrievedbytheexception’swhat ()function:

what.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>//Includest ringsupport .# include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringaninitializedst ringvariableint main(){

st ringlang=“C++”;//Addmorestatementshere.return0;

}

Inthemainfunction,insertat ryblockcontainingastatementattemptingtoerasepartofthest ringvariablet ry{lang.erase(4,6);}

Next,insertacatchblockcontainingastatementtosendadescriptiontostandarderroroutputbythecerrfunctioncatch(except ion&error){cerr<<“Except ion:”<<error.what ()<<endl;}

Save,compile,andruntheprogramtoseetheerrordescriptionofthecaught

Page 174: C++ Programming in easy steps, 5th Edition

exception

Theerrordescriptionwillvaryfordifferentcompilers–theVisualC++compilerdescribestheexceptionerrorinthisexampleasan“invalidstringposition”.

TheC++<stdexcept>librarydefinesanumberofexceptionclasses.Itsbaseclassisnamed“exception”,fromwhichotherclassesarederived,categorizingcommonexceptions.

Eachoftheexceptionclassesarelistedinthetablebelow,illustratingtheirrelationshipanddescribingtheirexceptiontype:

Thecoutfunctionsendsdatatostandardoutput,whereasthecerrfunctionsendserrordatatostandarderroroutput.Thesearesimplytwodifferentdatastreams.

Whenthe<stdexcept>libraryismadeavailabletoaprogram,byaddingan#include<stdexcept>preprocessordirective,theexceptionclassescanbeusedtoidentifythetypeof

Page 175: C++ Programming in easy steps, 5th Edition

exceptionthrowntoacatchblock.

Thespecificexceptionclassnamecanappear,inplaceofthegeneralexcept iontype,withinthecatchblock’sparentheses.

Theexampledescribedheredemonstratestheuseofstandardexceptions.

Multiplecatchblockscanbeusedinsuccession,muchlikecasestatementsinaswitchblock,tohandleseveraltypesofexception.

Additionally,exceptionscanbeproducedmanuallybythethrowkeyword.Thiscanbeusedtocreateanyofthelogic_errorandrunt ime_errorexceptionsinthetableabove.Optionally,acustomerrormessagecanbespecifiedformanualexceptions,whichcanberetrievedbyitswhat ()function.

Page 176: C++ Programming in easy steps, 5th Edition
Page 177: C++ Programming in easy steps, 5th Edition

HandlingerrorsExceptiontypeinformationcanbeprovidedbyincludingtheC++standard<typeinfo>library.Itst ypeid()functionacceptsanexceptionargumentsoitsname()functioncanreturnthetypename:

except.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<stdexcept>//Support standardexcept ions.#include<typeinfo>//Support typeinformat ion.#include<fst ream>#include<st ring>#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatement,twoinitializedvariabledeclarations,andastatementoutputtingatextmessageint main(){

st ringlang=“C++”;int num=1000000000;//Onebillion.//Try-catchblockgoeshere.cout <<“Programcont inues...”<<endl;return0;

}

Inthemainfunction,insertat ryblockcontainingastatementattemptingtoreplacepartofthest ringvaluet ry{lang.replace(100,1,“C”);}

Afterthet ryblock,addacatchblocktohandlearangeexceptionthensave,compile,andruntheprogramcatch(out_of_range&e){

cerr<<“RangeExcept ion:”<<e.what ()<<endl;cerr<<“Except ionType:”<<typeid(e).name();cerr<<endl<<“Programterminated.”<<endl;return-1;

}

Page 178: C++ Programming in easy steps, 5th Edition

Theout_of_rangeerroroccursbecausethereplace()functionistryingtobeginerasingatthe100thcharacter,butthestringvariablehasonlythreecharacters.

Replacethestatementinthet ryblockwithoneattemptingtoresizethest ringvariablelang.resize(3*num);

Afterthecatchblock,addasecondcatchblocktohandlegeneralexceptionscatch(except ion&e){

cerr<<“Except ion:”<<e.what ()<<endl;cerr<<“Except ionType:”<<typeid(e).name()<<endl;

}

Save,compile,andruntheprogramagaintoseetheexceptionhandledbythesecondcatchblock

Replacethestatementinthet ryblockwithoneattemptingtoopenanon-existentfileifst reamreader(“nonsuch.txt”);if(!reader)throwlogic_error(“Filenot found”);

Save,compile,andruntheprogramoncemoretoseetheexceptionhandledagainbythesecondcatchblock,andthespecifiedcustomerrormessage

Page 179: C++ Programming in easy steps, 5th Edition

Theorderofcatchblockscanbeimportant–placingtheexceptionerrorhandlerbeforetheout_of_rangeerrorhandlerwouldallowanout_of_rangeerrortobehandledbythe(higherlevel)exceptionhandler.

Anexceptionobjectistypicallygiventhename“e”–asseenhere.

Page 180: C++ Programming in easy steps, 5th Edition
Page 181: C++ Programming in easy steps, 5th Edition

Summary• TheC++<fst ream>libraryprovidesfunctionsforworkingwithfilesasifst reaminputor

ofst reamoutputstreamobjects.

• Uponcompletion,astream’sclose()functionshouldbecalled.

• Filemodescanbeusedtocontrolthebehaviorofastream.

• Aninputstream’sget ()functionreadsonecharacteratatime.

• Theget line()functioncanbeusedtoreadalineatatimefromaninputstream.

• Optionally,theget line()functioncanhaveathirdargumentspecifyingadelimitercharacteratwhichtostopreading.

• Insertionoperatorscanbeusedwiththecinandcout functionstomodifytheirbehavior.

• Thecout .width()functionsetsthewidthoftheoutputstream.

• Thecout .fill()functionspecifiesacharactertooccupyanyemptyportionoftheoutput.

• Thecout .precision()functiondetermineshowmanydecimalplacestodisplaywhentheoutputisafloatingpointnumber.

• Abadlyperformingprogrammaycontainsyntaxerrors,logicerrors,orexceptionerrors.

• At ryblockcanbeusedtoenclosestatementsthat,undercertainconditions,maycauseanexceptionerror.

• Acatchblockcanbeusedtohandleexceptionerrorsproducedinitsassociatedt ryblock.

• Exceptionerrorsthatoccurinat ryblockareautomaticallythrowntotheassociatedcatchblock,orcanbemanuallythrownusingthethrow()function.

• TheC++<stdexcept>librarydefinesanumberofexceptionclassesthatcategorizecommonexceptions,andthe<typeinfo>libraryprovidesexceptiontypeinformation.

Page 182: C++ Programming in easy steps, 5th Edition

6

Pointingtodata

ThischapterdemonstrateshowtoproduceefficientC++programs,utilizingpointersandreferences.

UnderstandingdatastorageGettingvalueswithpointersDoingpointerarithmeticPassingpointerstofunctionsMakingarraysofpointersReferencingdataPassingreferencestofunctionsComparingpointers&referencesSummary

Page 183: C++ Programming in easy steps, 5th Edition
Page 184: C++ Programming in easy steps, 5th Edition

UnderstandingdatastorageInordertounderstandC++pointersitishelpfultounderstandhowdataisstoredonyourcomputer.Envisionthecomputer ’smemoryasaverylongrowofsequentiallynumberedslots,whichcaneachcontainonebyteofdata.Whenavariableisdeclaredinaprogram,themachinereservesanumberofslotsatwhichtostoredataassignedtothatvariable.Thenumberofslotsitreservesdependsuponthevariable’sdatatype.Whentheprogramusesthevariablenametoretrievestoreddata,itactuallyaddressesthenumberofthevariable’sfirstreservedslot.

Comparisoncanbedrawntoalongrowofsequentially-numberedhousesthatcaneachaccommodateadifferentfamily.Anyfamilycanbeexplicitlyreferencedbyaddressingtheirhousenumber.

Theslot(house)numbersincomputermemoryareexpressedinhexadecimalformatandcanberevealedbythe&referenceoperator.

address.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringthreeinitializedvariablesint main(){

int num=100;doublesum=0.0123456789;st ringtext =“C++Fun”;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementstooutputthememoryaddressofthefirstslotofeachvariablecout <<“Integervariablestartsat :“<<&num<<endl;cout <<“Doublevariablestartsat :“<<&sum<<endl;cout <<“St ringvariablestartsat :“<<&text <<endl;

Save,compile,andruntheprogramtoseethethreememoryaddresses

Page 185: C++ Programming in easy steps, 5th Edition

Oncememoryspacehasbeenreservedbyavariabledeclaration,avalueoftheappropriatedatatypecanbestoredthereusingthe=assignmentoperator.Forexample,num=100takesthevalueonitsright(100)andputsitinthememoryreferencedbythenamedvariableonitsleft(num).

Thelocationaddressesaredynamicallyallocated–sowillvaryfromthoseinthisscreenshot.

Theoperandtotheleftofthe=assignmentoperatoriscalledits“L-value”andtheoperandtoitsrightiscalledits“R-value”.Considerthe“L”inL-valuetomean“Location”andconsiderthe“R”inR-valuetomean“Read”.

OneimportantruleinC++programminginsiststhatanR-valuecannotappeartotheleftofthe=assignmentoperator,butanL-valuemayappearoneitherside.CodethatplacesanR-valuetotheleftofan=assignmentoperatorwillnotcompile:

Justbeforethereturnstatement,insertstatementsplacingR-valuesincorrectlytotheleftofassignmentoperators200=num;5.5=sum;“Badassignments”=text ;

Save,andattempttorecompiletheprogramtoseetheerrorscausedbyincorrectlyplacedR-values

Page 186: C++ Programming in easy steps, 5th Edition

L-valuesarecontainersbutR-valuesaredata.

Page 187: C++ Programming in easy steps, 5th Edition
Page 188: C++ Programming in easy steps, 5th Edition

GettingvalueswithpointersPointersareausefulpartofefficientC++programming–theyaresimplyvariablesthatstorethememoryaddressofothervariables.

Pointervariablesaredeclaredinthesamewaythatothervariablesaredeclared,butthedatatypeissuffixedbya“*”character.Thisdenotes,inadeclaration,thatthevariablewillbeapointer.Alwaysrememberthatthepointer ’sdatatypemustmatchthatofthevariabletowhichitpoints.

Apointervariableisinitializedbyassigningitthememoryaddressofanothervariable,usingthe&referenceoperator.Theassignmentcanbemadeeitherinthedeclarationstatement,orinaseparatestatementafterthedeclaration.Referencingapointervariablebyitsnamealonewillsimplyrevealthememoryaddressthatitcontains.

Afterapointervariablehasbeeninitialized,eitherinthedeclarationorbyasubsequentassignment,it“points”tothevariableattheaddresswhichitcontains.Usefully,thismeansthatthevalueofthevariabletowhichitpointscanbereferencedbyprefixingthepointernamewiththe*dereferenceoperator:

deref.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringtworegularinitializedintegervariablesint main(){

int a=8,b=16;//Addmorestatementshere.return0;

}

Inthemainfunction,insertastatementtodeclare,andinitializeapointerwiththememoryaddressofthefirstintegervariableint *aPt r=&a;//aPt rassignedaddressofa.

Insertastatementtodeclareasecondpointer,theninitializeitwiththeaddressofthesecondintegervariableint *bPt r;//bPt rdeclared.

Page 189: C++ Programming in easy steps, 5th Edition

bPt r=&b;//bPt rassignedaddressofb.

Next,insertstatementstooutputtheactualmemoryaddressofeachpointercout <<“Addressesofpointers...”<<endl;cout <<“aPt r:”<<&aPt r<<endl;cout <<“bPt r:”<<&bPt r<<endl<<endl;

Now,insertstatementstooutputthememoryaddressstoredinsideeachpointercout <<“Valuesinpointers...”<<endl;cout <<“aPt r:”<<aPt r<<endl;cout <<“bPt r:”<<bPt r<<endl<<endl;

Finally,insertstatementstooutputthevaluesstoredatthememoryaddressstoredineachpointer–thevalueofthevariablestowhichthepointerspointcout <<“Valuesinaddressespointedto...”<<endl;cout <<“a:”<<*aPt r<<endl;cout <<“b:”<<*bPt r<<endl;

Save,compile,andruntheprogramtoseethepointeraddressesandthestoredvalues

The*dereferenceoperatorisalternativelyknownasthe“indirection”operator.

Thememoryaddressesaredynamicallyallocated–sowillvaryfromthoseinthisscreenshot.

Page 190: C++ Programming in easy steps, 5th Edition
Page 191: C++ Programming in easy steps, 5th Edition

DoingpointerarithmeticOnceapointervariablehasbeeninitializedwithamemoryaddress,itcanbeassignedanotheraddress,orchangedusingpointerarithmetic.

The++incrementoperatororthe--decrementoperatorwillmovethepointeralongtothenextorpreviousaddressforthatdatatype–thelargerthedatatype,thebiggerthejump.

Evenlargerjumpscanbeachievedusingthe+=and-=operators.

Pointerarithmeticisespeciallyusefulwitharrays,becausetheelementsinanarrayoccupyconsecutivememoryaddresses.Assigningjustthenameofanarraytoapointerautomaticallyassignsittheaddressofthefirstelement.Incrementingthepointerbyonemovesthepointeralongtothenextelement.

point.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringaninitializedintegerarrayof10elementsint main(){

int nums[]={1,2,3,4,5,6,7,8,9,10};//Addmorestatementshere.return0;

}

Inthemainfunction,insertastatementtodeclareapointer,initializedwiththememoryaddressofthefirstelementintheintegerarrayint *pt r=nums;

Next,insertastatementtooutputthememoryaddressofthefirstelementoftheintegerarray,anditsvaluecout <<endl<<“pt rat :”<<pt r<<“gets:”<<*pt r;

Now,incrementthepointerandoutputitsnewmemoryaddress–thatofthesecondelementintheintegerarraypt r++;cout <<endl<<“pt rat :”<<pt r<<“gets:”<<*pt r;

Page 192: C++ Programming in easy steps, 5th Edition

Incrementthepointeragain,andoutputitsnewmemoryaddress–thatofthethirdelementintheintegerarraypt r++;cout <<endl<<“pt rat :”<<pt r<<“gets:”<<*pt r;

Decrementthepointerbytwoplacesandoutputitsmemoryaddress–thatofthefirstelementinthearraypt r-=2;cout <<endl<<“pt rat :”<<pt r<<“gets:”<<*pt r;cout <<endl;

Now,insertalooptooutputthevaluestoredineachelementoftheintegerarrayfor(int i=0;i<10;i++){

cout <<endl<<“Element :“<<i;cout <<“Value:“<<*pt r;pt r++;

}cout <<endl;

Save,compile,andruntheprogramtoseethepointeraddressesandthestoredvalues

The*=,/=,and%=operatorscannotbeusedtomoveapointer.

Thenameofanarrayactslikeapointertoitsfirstelement.

Page 193: C++ Programming in easy steps, 5th Edition
Page 194: C++ Programming in easy steps, 5th Edition

PassingpointerstofunctionsPointerscanaccessthedatastoredinthevariabletowhichtheypointusingthe*dereferenceoperator.Thiscanalsobeusedtochangethestoreddatabyassigninganewvalueoftheappropriatedatatype.

Additionally,pointerscanbepassedtofunctionsasarguments–withasubtlydifferenteffecttopassingvariablesasarguments:

• Whenvariablesarepassedtofunctions,theirdataispassed“byvalue”toalocalvariableinsidethefunction–sothatthefunctionoperatesonacopyoftheoriginalvalue.

• Whenpointersarepassedtofunctions,theirdataispassed“byreference”–sothatthefunctionoperatesontheoriginalvalue.

Thebenefitofpassingbyreferenceallowsfunctionstodirectlymanipulatevariablevaluesdeclaredwithinthecallingfunction.

fnptr.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Afterthepreprocessorinstructions,declaretwofunctionprototypestoeachacceptasinglepointerargumentvoidwriteOutput (int *);voidcomputeTriple(int *);

Addamainfunctioncontainingafinalreturnstatementanddeclaringaninitializedregularintegervariableint main(){

int num=5;//Addmorestatementshere.return0;

}

Inthemainfunction,insertasecondvariabledeclarationthatinitializesapointerwiththeaddressoftheregularintegervariableint *pt r=&num;

Afterthemainfunctionblock,defineafunctiontooutputthecurrentvalueofa

Page 195: C++ Programming in easy steps, 5th Edition

variabletowhichapointerpointsvoidwriteOutput (int *value){

cout <<“Current value:”<<*value<<endl;}

DefineanotherfunctiontomultiplythecurrentvalueofavariabletowhichapointerpointsvoidcomputeTriple(int *value){

*value*=3;//Mult iplyandassigndereferencedvalue.}

Inthemainfunction,passapointerargumenttoafunctiontooutputthevariablevaluetowhichitpointswriteOutput (pt r);

Next,usethepointertoincreasethevariablevalue,thendisplayitsnewvalue*pt r+=15;//Addandassignadereferencedvalue.writeOutput (pt r);

Now,passapointerargumenttoafunctiontomultiplythevariabletowhichitpoints,thendisplayitsnewvaluecomputeTriple(pt r);writeOutput (pt r);

Save,compile,andruntheprogramtoseethecomputedvaluesoutput

Thefunctionprototypeanddefinitionmustbothcontainapointerargument.

Functionsthatoperatedirectlyonvariableswithinthecallingfunctionneednoreturnstatement.

Page 196: C++ Programming in easy steps, 5th Edition
Page 197: C++ Programming in easy steps, 5th Edition

MakingarraysofpointersAvariableoftheregularchardatatypecanbeassignedasinglecharactervalue,butapointertoaconstantchararraycanusefullybeassignedastringofcharacters.Thestringisactuallystoredasanarrayofcharacters,withonecharacterperelement,butreferencingthecharpointerwillautomaticallyretrievetheentirestring.

Thisabilitytoretrieveastringvaluefromacharpointerusingjustitsvariablenameresemblesthewaythatastringcanberetrievedfromaregularchararrayusingitsvariablename.

Multiplestringscanbestoredinaconstantcharpointerarray,withonestringperelement.Youcanevenstoremultiplecharpointerarraysina“master”charpointerarray–onearrayperelement.

arrptr.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringtwoinitializedvariables–aregularcharacterarray,andacharacterpointerwithidenticalst ringvaluesint main(){

charlet ters[8]={‘C’,‘+’,‘+’,‘‘,‘F’,‘u’,‘n’,‘\0’};const char*text =“C++Fun”;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementstodeclare,andinitializetwofurthercharacterpointervariables,withuniquest ringvaluesconst char*term=“Element :”;const char*lang=“C++”;

Next,insertastatementtodeclareacharacterpointerarray,initializedwiththreest ringvaluesconst char*ap1[3]={“Great ”,“Program”,“Code”};

Page 198: C++ Programming in easy steps, 5th Edition

Charactervaluesmustbeenclosedinsinglequotes,butstringvaluesmustbeenclosedindoublequotes–evenwhentheyarebeingassignedtoacharpointer.

Now,insertastatementtodeclareasecondcharacterpointerarray,initializedwiththreestringvalues–makingoneofthepointervariablesitsfirstelementvalueconst char*ap2[3]={lang,“is”,“Fun”};

Declaretwo“master”characterpointerarrays,eachinitializedwiththreeelementsofthecharpointerarraysconst char*ap3[3]={ap2[0],ap2[1],ap1[0]};const char*ap4[3]={ap1[2],ap2[1],ap2[2]};

Afterthedeclarations,insertstatementstooutputtheidenticalst ringvaluesofthefirsttwovariablescout <<let ters<<endl;cout <<text <<endl;

Next,insertaloopcontainingastatementtooutputthevaluewithinacharacterpointerandtheiterationnumberfor(int i=0;i<3;i++){

cout <<term<<i<<““;}

Withintheloopblock,insertstatementstooutputeachelementvalueofthefourcharacterpointerarrayscout <<ap1[i]<<“”;cout <<ap2[i]<<“”;cout <<ap3[i]<<“”;cout <<ap4[i]<<endl;

Save,compile,andruntheprogramtoseethecharacterstringoutput

Page 199: C++ Programming in easy steps, 5th Edition

Toincludeaspaceinachararray,theassignmentmusthaveaspacebetweenthequotesas‘‘–twosinglequotestogether(‘‘)isregardedasanemptyelementandcausesacompilererror.

Rememberthatthefinalelementofachararraymustcontainthespecial\0charactertodesignatethatarrayasastring.

Page 200: C++ Programming in easy steps, 5th Edition
Page 201: C++ Programming in easy steps, 5th Edition

ReferencingdataAC++“reference”isanaliasforavariableoranobjectinaprogram.Areferencemustbeinitializedwithinitsdeclaration,byassigningitthenameofthevariableorobjecttowhichitrefers.Fromthenon,thereferenceactsasanalternativenamefortheitemtowhichitrefers–anythingthathappenstothereferenceisreallyimplementedonthevariableorobjecttowhichitrefers.

Areferencedeclarationfirststatesitsdatatype,matchingthatoftheitemtowhichitwillrefer,suffixedbyan&characterdenotingthatvariablewillbeareference,andachosenname.Finally,thedeclarationusesthe=operatortoassociateavariableorobject.

Onceareferencehasbeencreated,itwillalwaysrefertotheitemtowhichitwasinitialized−adifferentitemcannotbeassignedtothatreference.

Traditionally,areferenceisnamedwiththenameoftheassociatedvariableorobject,butwithanuppercasefirstletterandthewholenameprefixedbyan“r”.Forexample,adeclarationtocreateareferencetoanintegervariablenamed“num”lookslikethis:

int&rNum=num;

Notethatthepurposeofthe&referenceoperatoriscontext-sensitivesothatitdeclaresareferencewhenusedasanL-value,ontheleftsideofthe=operator,otherwiseitreturnsamemoryaddresswhenusedasanR-value.

Areferenceissuchatruealiastoitsassociateditem,thatqueryingitsmemoryaddressreturnstheaddressofitsassociateditem–thereisnowaytodiscovertheaddressofthereferenceitself.

ref.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementanddeclaringtwovariables–a

Page 202: C++ Programming in easy steps, 5th Edition

regularintegervariableandareferencetothatvariableint main(){

int num;int&rNum=num;//Addmorestatementshere.return0;

}

Inthemainfunction,insertastatementassigninganinitialvaluetotheintegervariableviaitsreferencerNum=400;

Next,insertstatementstooutputthestoredvalue,bothdirectlyandviaitsreferencecout <<“Valuedirect :”<<num<<endl;cout <<“Valueviareference:”<<rNum<<endl;

Now,insertstatementstooutputthememoryaddress,bothdirectlyandviaitsreferencecout <<“Addressdirect :”<<&num<<endl;cout <<“Addressviareference:”<<&rNum<<endl;

InsertastatementtomanipulatethevaluestoredinthevariableviaitsreferencerNum*=2;

Oncemore,outputthestoredvalue,bothdirectlyandviaitsreferencecout <<“Valuedirect :”<<num<<endl;cout <<“Valueviareference:”<<rNum<<endl;

Save,compile,andruntheprogramtoseethevaluesandmemoryaddress

Thecompilerdecideshowtousethe&referenceoperatoraccordingtoitscontext.

Page 203: C++ Programming in easy steps, 5th Edition

Areferenceisalwaysanaliasfortheitemassociatedinitsdeclarationstatement.

Page 204: C++ Programming in easy steps, 5th Edition
Page 205: C++ Programming in easy steps, 5th Edition

PassingreferencestofunctionsReferencesprovideaccesstothedatastoredinthevariabletowhichtheyrefer,justlikethevariableitself,andcanbeusedtochangethestoreddatabyassigninganewvalueoftheappropriatedatatype.

Additionally,referencescan,likepointers,bepassedtofunctionsasarguments:

• Whenvariablesarepassedtofunctions,theirdataispassed“byvalue”toalocalvariableinsidethefunction–sothatthefunctionoperatesonacopyoftheoriginalvalue.

• Whenreferencesarepassedtofunctions,theirdataispassed“byreference”–sothefunctionoperatesontheoriginalvalue.

Thebenefitofpassingbyreferenceallowsfunctionstodirectlymanipulatevariablevaluesdeclaredwithinthecallingfunction.

fnref.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Afterthepreprocessorinstructions,declaretwofunctionprototypestoeachacceptasinglereferenceargumentvoidwriteOutput (int&);voidcomputeTriple(int&);

Addamainfunctioncontainingafinalreturnstatementanddeclaringaninitializedregularintegervariableint main(){

int num=5;//Addmorestatementshere.return0;

}

Inthemainfunction,insertasecondvariabledeclaration,initializingareferenceasanaliasoftheintegervariableint&ref=num;

Page 206: C++ Programming in easy steps, 5th Edition

Thisexamplemayseemfamiliar,asitrecreatestheexamplehere–butreplacespointerswithreferences.

Afterthemainfunctionblock,defineafunctiontooutputthecurrentvalueofavariabletowhichareferencerefersvoidwriteOutput (int&value){

cout <<“Current value:”<<value<<endl;}

DefineanotherfunctiontomultiplythecurrentvalueofavariabletowhichareferencerefersvoidcomputeTriple(int&value){

value*=3;//Mult iplyandassignareferencedvalue.}

Inthemainfunction,passareferenceargumenttoafunctiontooutputthevariablevaluetowhichitreferswriteOutput (ref);

Next,usethereferencetoincreasethevariablevalue,thendisplayitsnewvalueref+=15;//Addandassignareferencedvalue.writeOutput (ref);

Now,passareferenceargumenttoafunctiontomultiplythevariabletowhichitrefers,thendisplayitsnewvaluecomputeTriple(ref);writeOutput (ref);

Save,compile,andruntheprogramtoseethecomputedvaluesoutput

Page 207: C++ Programming in easy steps, 5th Edition

Thefunctionprototypeanddefinitionmustbothcontainareferenceargument.

Functionsthatoperatedirectlyonvariableswithinthecallingfunctionneednoreturnstatement.

Page 208: C++ Programming in easy steps, 5th Edition
Page 209: C++ Programming in easy steps, 5th Edition

Comparingpointers&referencesPointersandreferencescanbothbeusedtorefertovariablevaluesandtopassthemtofunctionsbyreferenceratherthanbyvalue.Technically,passingbyreferenceismoreefficientthanpassingbyvalue,sotheuseofpointersandreferencesistobeencouraged.

Thedecisionwhethertouseapointerorareferenceisdeterminedbytheprogramrequirements.C++programmersgenerallyprefertousereferenceswhereverpossible,astheyareeasiertouseandeasiertounderstandthanpointers.Referencesmust,however,obeycertainruleswhichcanmaketheuseofpointersnecessary:

Rule: References: Pointers:

Canbedeclaredwithoutinitialization No Yes

Canbereassigned No Yes

Cancontaina0(null)value No Yes

Easiesttouse Yes No

Asageneralrule,thechoicebetweenusingareferenceorapointercanbedeterminedbyfollowingtheseguidelines:

• Ifyoudon’twanttoinitializeinthedeclaration,useapointeror

• Ifyouwanttobeabletoreassignanothervariable,useapointerotherwise

• Alwaysuseareference

Areferencemustbeinitializedinthedeclarationtorefertoavariableorobject–thenalwaysreferstothatitem.

Pointersaremoreflexiblethanreferences,however,andcanevenpointtofunctions.Inthiscase,thepointerdeclarationmustpreciselymatchthereturndatatypeandargumentstothoseofthefunctiontowhichitpoints.Additionally,thepointernamemustbeenclosedwithinparenthesesinthedeclarationtoavoidcompilererrors.Thefunctionpointercanthenbeassignedafunctionbyname,sothatfunctioncanbecalledviathepointer.

Page 210: C++ Programming in easy steps, 5th Edition

pref.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Afterthepreprocessorinstructions,defineaninlinefunctiontooutputthetotaloftwopassedargumentsinlinevoidadd(int&a,int *b){cout <<“Total:”<<(a+*b)<<endl;}

Addamainfunctioncontainingafinalreturnstatementanddeclarationscreatingtworegularintegervariables,onereference,andtwopointersint main(){

int num=100,sum=500;int&rNum=num;int *pt r=&num;void(*fn)(int&a,int *b)=add;//Addmorestatementshere.return0;

}

Inthemainfunction,insertstatementstooutputthefirstintegervariablevaluesviathereferenceandpointercout <<“Reference:”<<rNum<<endl;cout <<“Pointer:”<<*pt r<<endl;

Now,assignthesecondintegervariabletothepointerandoutputitsvalueviathepointer,thencallthefunctionpointertooutputthesumofthevariablevaluespt r=&sum;cout <<“Pointernow:”<<*pt r<<endl;fn(rNum,pt r);

Save,compile,andruntheprogramtoseetheoutput

Page 211: C++ Programming in easy steps, 5th Edition

Cprogrammerstendtoputthe&and*charactersbeforethevariablenames,butinC++itisusualtoputthemafterthedatatype–asthefeatureisapropertyofthedatatype,notthename.

Page 212: C++ Programming in easy steps, 5th Edition
Page 213: C++ Programming in easy steps, 5th Edition

Summary• Dataisstoredincomputermemorywithinsequentiallynumberedaddresses.

• Operandstotheleftofan=operatorareL-values,andthosetoitsrightareR-values.

• AnR-valuemayonlyappeartotherightofan=operator.

• Apointerisavariablethatstoresthememoryaddressofanothervariable–thattowhichitpoints.

• The*characterappearsasanL-valueinapointerdeclaration,indicatingthatthestatementwillcreateapointervariable.

• Oncedeclared,the*dereferenceoperatorcanbeusedtoreferencethevaluewithinavariabletowhichapointerpoints.

• Pointerarithmeticcanbeusedtoiteratethroughthevaluesstoredinarrayelements.

• Avariableispassedtoafunctionbyvalue,whereaspointersandreferencesarepassedbyreference.

• Passingbyreferenceallowsthereceivingfunctiontodirectlymanipulatevariablesdeclaredwithinthecallingfunction.

• Astringvaluecanbeassignedtoapointerofthechardatatype,andthewholestringretrievedusingthepointername.

• Eachelementinapointerarraycanstoredataorapointer.

• Areferenceisnotavariable,butmerelyanaliasforavariable.

• The&characterappearsasanL-valueinareferencedeclaration,indicatingthatthestatementwillcreateanalias.

• The&referenceoperatorcanbeusedtoreferencethememoryaddressstoredwithinapointer.

• Referencesareeasiertousethanpointersbut,unlikepointers,areferencemustalwaysbeinitializedinitsdeclarationandcanneverbeassignedadifferentvariable.

Page 214: C++ Programming in easy steps, 5th Edition

7

Creatingclassesandobjects

Thischapterintroducesthetopicsofencapsulationandinheritance–thefirsttwoprinciplesofC++ObjectOriented

Programming.

EncapsulatingdataCreatinganobjectCreatingmultipleobjectsInitializingclassmembersOverloadingmethodsInheritingclasspropertiesCallingbaseconstructorsOverridingbasemethodsSummary

Page 215: C++ Programming in easy steps, 5th Edition
Page 216: C++ Programming in easy steps, 5th Edition

EncapsulatingdataAclassisadatastructurethatcancontainbothvariablesandfunctionsinasingleentity.Thesearecollectivelyknownasits“members”,andthefunctionsareknownasits“methods”.

Accesstoclassmembersfromoutsidetheclassiscontrolledby“accessspecifiers”intheclassdeclaration.Typically,thesewilldenyaccesstothevariablemembers,butallowaccesstomethodsthatcanstoreandretrievedatafromthosevariablemembers.Thistechniqueof“datahiding”ensuresthatstoreddataissafelyencapsulatedwithintheclassvariablemembers,andisthefirstprincipleofObjectOrientedProgramming(OOP).

Aclassdeclarationbeginswiththeclasskeyword,followedbyaspace,thenaprogrammer-specifiedname–adheringtotheusualC++namingconventions,butbeginninginuppercase.Next,cometheaccessspecifiersandclassmembers,containedwithinapairofbraces.Everyclassdeclarationmustendwithasemicolonaftertheclosingbrace–sotheclassdeclarationsyntaxlookslikethis:

classClassName{

accessspecifier:member1;member2;

accessspecifier:member3;member4;

};

Anaccessspecifiermaybeanyoneofthekeywordspublic,private,orprotectedtospecifyaccessrightsforitslistedmembers:

• Publicmembersareaccessiblefromanyplacewheretheclassisvisible

• Privatemembersareaccessibleonlytoothermembersofthesameclass

• Protectedmembersareaccessibleonlytoothermembersofthesameclassandtomembersofclassesderivedfromthatclass

Bydefault,allclassmembershaveprivateaccess–soanymembersthatappearintheclassdeclarationwithoutanaccessspecifierwillhaveprivateaccess.

Page 217: C++ Programming in easy steps, 5th Edition

Derivedclasses,whichusetheprotectedaccessspecifier,areintroducedlaterinthischapter.

Anyreal-worldobjectcanbedefinedbyitsattributesandbyitsactions.Forexample,adoghasattributessuchasage,weight,andcolor,andactionsitcanperformsuchasbark.TheclassmechanisminC++providesawaytocreateavirtualdogobjectwithinaprogram,wherethevariablemembersofaclasscanrepresentitsattributes,andthemethodsrepresentitsactions:

classDog{

private://Thedefault accesslevel.int age,weight ;st ringcolor;

public:voidbark();//...Plusmethodstostore/ret rievedata.

};

Whileaprogramclasscannotperfectlyemulateareal-wordobject,theaimistoencapsulateallrelevantattributesandactions.

Itisimportanttorecognizethataclassdeclarationonlydefinesadatastructure–inordertocreateanobjectyoumustdeclarean“instance”ofthatdatastructure.ThisisachievedinjustthesamewaythatinstancesaredeclaredofregularC++datatypes:

int num; //Createsaninstancenamed“num”.//oftheregularC++int datatype.

Dogfido; //Createsaninstancenamed“fido”.//oftheprogrammer-definedDogdatast ructure.

Alternatively,aninstanceobjectcanbecreatedbyspecifyingitsnamebetweentheclassdeclaration’sclosingbraceanditsfinalsemicolon.Multipleinstancescanbecreatedthisway,byspecifyingacomma-separatedlistofobjectnames.Forexample,theclassdeclarationlistedbelowcreatesfourinstanceobjectsoftheDogclassnamed“fido”,“pooch”,“rex”,and“sammy”.

classDog{

Page 218: C++ Programming in easy steps, 5th Edition

int age,weight ;st ringcolor;

public:voidbark();//...Plusmethodstostore/ret rievedata.

}fido,pooch,rex,sammy;

TheprincipleofencapsulationinC++programmingdescribesthegroupingtogetherofdataandfunctionalityinclassmembers–age,weight,colorattributesandbarkactionintheDogclass.

Itisconventionaltobeginclassnameswithanuppercasecharacterandobjectnameswithlowercase.

Page 219: C++ Programming in easy steps, 5th Edition
Page 220: C++ Programming in easy steps, 5th Edition

CreatinganobjectInordertoassignandretrievedatafromprivatemembersofaclass,specialpublicaccessormethodsmustbeaddedtotheclass.Theseare“setter”methods,toassigndata,and“getter”methods,toretrievedata.Accessormethodsareoftennamedasthevariabletheyaddress,withthefirstlettermadeuppercase,andprefixedby“set”or“get”respectively.Forexample,accessormethodstoaddressanagevariablemaybenamedsetAge()andgetAge().

object.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>#include<iost ream>usingnamespacestd;

Declareaclassnamed“Dog”classDog{};

BetweenthebracesoftheDogclassdeclaration,declarethreeprivatevariablemembersint age,weight ;st ringcolor;

Aftertheprivatevariables,addapublicaccessspecifierpublic:

Beginthepublicmemberslistbyaddingamethodtooutputast ringwhencalledvoidbark(){cout <<“WOOF!”<<endl;}

Addpublicsettermethods–toassignindividualvaluestoeachoftheprivatevariablesvoidsetAge(int yrs){age=yrs;}voidsetWeight (int lbs){weight =lbs;}voidsetColor(st ringhue){color=hue;}

Addpublicgettermethods–toretrieveindividualvaluesfromeachoftheprivatevariablesint getAge(){returnage;}int getWeight (){returnweight ;}st ringgetColor(){returncolor;}

Page 221: C++ Programming in easy steps, 5th Edition

Membersdeclaredbeforeanaccessspecifierareprivatebydefault,andremembertoaddafinalsemicolonaftereachclassdeclaration.

Intheclassdeclaration,noticethatallmethodsaredeclaredpublicandallvariablesaredeclaredprivate.Thisnotionof“publicinterface,privatedata”isakeyconceptwhencreatingclasses.

AftertheDogclassdeclaration,declareamainmethodcontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Betweenthebracesofthemainmethod,declareaninstanceoftheDogclassnamed“fido”Dogfido;

Addstatementscallingeachsettermethodtoassigndatafido.setAge(3);fido.setWeight (15);fido.setColor(“brown”);

Addstatementscallingeachgettermethodtoretrievetheassignedvaluescout <<“Fidoisa“<<fido.getColor()<<

“dog”<<endl;cout <<“Fidois“<<fido.getAge()<<

“yearsold”<<endl;cout <<“Fidoweighs“<<fido.getWeight ()<<

“pounds”<<endl;

Now,addacalltotheregularoutputmethodfido.bark();

Save,compile,andruntheprogramtoseetheoutput

Page 222: C++ Programming in easy steps, 5th Edition

Fido

Thisprogramwillgetmodifiedoverthenextfewpagesasnewfeaturesareincorporated.

Page 223: C++ Programming in easy steps, 5th Edition
Page 224: C++ Programming in easy steps, 5th Edition

CreatingmultipleobjectsAprogramcaneasilycreatemultipleobjects,simplybydeclaringmultipleinstancesofaclass,andeachobjectcanhaveuniqueattributesbyassigningindividualvalueswithitssettermethods.

Itisoftenconvenienttocombinethesettermethodsintoasinglemethodthatacceptsargumentsforeachprivatevariable.Thismeansthatallvaluescanbeassignedwithasinglestatementintheprogram,butthemethodwillcontainmultiplestatements.

Theclassdeclarationinthepreviousexamplecontainsshortmethodsofjustoneline,whicharecreated“inline”–entirelywithintheclassdeclarationblock.Wheremethodshavemorethantwolines,theyshouldnotbecreatedinline,butshouldinsteadbedeclaredasa“prototype”intheclassdeclarationblockanddefinedseparately–aftertheclassdeclaration.Thedefinitionmustprefixthemethodnamewiththeclassnameandthescoperesolutionoperator::toidentifytheclasscontainingitsprototype.

multiple.cpp

Renameacopyofthepreviousexample“object.cpp”asanewprogram“multiple.cpp”

IntheDogclassdeclaration,replacethethreesettermethodswithasinglecombinedsetterprototypethatspecifiestheargumentdatatypes–butnottheirnamesvoidsetValues(int ,int ,st ring);

AftertheDogclassdeclaration,addadefinitionblockfortheprototypeusingthe::scoperesolutionoperatortoidentifytheclassinwhichitresidesvoidDog::setValues(int age,int weight ,st ringcolor){

}

Noticethat,foreasyidentification,theargumentsarenamedwiththesamenamesasthevariablestowhichtheywillbeassigned.Whereaclassmethoddefinitionhasanargumentofthesamenameasaclassmember,thethis->classpointercanbeusedtoexplicitlyrefertotheclassmember.Forexample,this->agereferstotheclassmembervariable,whereasagereferstotheargument.

Page 225: C++ Programming in easy steps, 5th Edition

Notethataprototypeisastatement–soitmustendwithasemicolon.

Inthemethoddefinitionblock,insertthreestatementstoassignvaluesfrompassedargumentstoclassvariablesthis->age=age;this->weight =weight ;this->color=color;

Betweenthebracesofthemainmethod,replacethecallstothethreesettermethodsbyasinglecalltothecombinedsettermethod–passingthreeargumentsfido.setValues(3,15,“brown”);

Inthemainmethod,declareasecondinstanceoftheDogclassnamed“pooch”Dogpooch;

Addasecondcalltothecombinedsettermethod–passingthreeargumentsforthenewobjectpooch.setValues(4,18,“gray”);

Addstatementscallingeachgettermethodtoretrievetheassignedvaluescout <<“Poochisa“<<pooch.getAge();cout <<“yearold“<<pooch.getColor();cout <<“dogwhoweighs“<<pooch.getWeight ();cout <<“pounds.”;

Now,addsecondcalltotheregularoutputmethodpooch.bark();

Save,compile,andruntheprogramtoseetheoutput

Page 226: C++ Programming in easy steps, 5th Edition

Wheretheargumentnameandclassmembernamesaredifferent,thethis->classpointerisnotneededinthesettermethoddefinitions.

Page 227: C++ Programming in easy steps, 5th Edition
Page 228: C++ Programming in easy steps, 5th Edition

InitializingclassmembersClassvariablememberscanbeinitializedbyaspecial“constructor”methodthatiscalledwheneveraninstanceoftheclassiscreated.Theconstructormethodisalwaysnamedexactlyastheclassname,andrequiresargumentstosettheinitialvalueofclassvariables.

Whenaconstructormethodisdeclared,anassociated“destructor”methodshouldalsobedeclared–thatiscalledwheneveraninstanceoftheclassisdestroyed.Thedestructormethodisalwaysnamedastheclassname,prefixedbya~tildecharacter.

Constructoranddestructormethodshavenoreturnvalue,andarecalledautomatically–theycannotbecalledexplicitly.

Valuestoinitializeclassvariablesarepassedtotheconstructormethodinthestatementcreatinganobject,inparenthesesfollowingtheobjectname.

constructor.cpp

Renameacopyofthepreviousexample“multiple.cpp”asanewprogram“constructor.cpp”

InthepublicsectionoftheDogclassdeclaration,replacethesetValuesmethodprototypewiththisconstructorprototypeDog(int ,int ,st ring);

Now,addanassociateddestructorprototype~Dog();

AftertheDogclassdeclaration,replacethesetValuesdefinitionblockwithaconstructordefinitionblockDog::Dog(int age,int weight ,st ringcolor){

}

Intheconstructordefinitionblock,insertthreestatementstoassignvaluesfrompassedargumentstoclassvariablesthis->age=age;this->weight =weight ;this->color=color;

Page 229: C++ Programming in easy steps, 5th Edition

Thedefinitionofaclassmethodisalsoknownasthemethod“implementation”.

Aftertheconstructordefinition,addadestructordefinitionblockDog::~Dog(){

}

Inthedestructordefinition,insertastatementtooutputaconfirmationwheneveraninstanceobjectgetsdestroyedcout <<“Object dest royed.”<<endl;

Inthemainmethod,editthestatementcreatingthe“fido”object–topassvaluestoitsconstructormethodDogfido(3,15,“brown”);

Similarly,editthestatementcreatingthe“pooch”object–topassvaluestotheconstructormethodDogpooch(4,18,“gray”);

DeletethestatementscallingthesetValuesmethodofthe“fido”and“pooch”objects–theconstructorhasnowreplacedthatmethod

Save,compile,andruntheprogram–seetheoutputappearasbefore,plusconfirmationwhentheobjectsgetdestroyed

Thedestructordefinitionbeginswiththeclassname“Dog”,thescoperesolutionoperator“::”,thenthedestructormethodname“~Dog”.

Page 230: C++ Programming in easy steps, 5th Edition

Althoughtheinitialvaluesofthevariablemembersaresetbytheconstructor,settermethodscanbeaddedtosubsequentlychangethevalues–andthosenewvaluescanberetrievedbythegettermethods.

Page 231: C++ Programming in easy steps, 5th Edition
Page 232: C++ Programming in easy steps, 5th Edition

OverloadingmethodsJustasC++allowsfunctionstobeoverloaded,classmethodscanbeoverloadedtoo–includingconstructormethods.Anoverloadedconstructormethodisusefultoassigndefaultvaluestomembervariableswhenanobjectiscreatedwithoutpassingvaluestotheconstructor.

overloaded.cpp

Renameacopyofthepreviousexample“constructor.cpp”asanewprogram“overloaded.cpp”

InthepublicsectionoftheDogclassdeclaration,addinlineanoverloadedbarkmethod–tooutputapassedstringargumentwhencalledvoidbark(st ringnoise){cout <<noise<<endl;}

Now,declareaconstructormethodprototypethattakesnoarguments(adefaultconstructormethod)andanoverloadedconstructormethodprototypethattakestwoargumentsDog();Dog(int ,int );

AftertheDogclassdeclaration,addadefinitionforthedefaultconstructormethod–assigningdefaultvaluestoclassvariableswhenanobjectiscreatedwithoutpassinganyargumentsDog::Dog(){

age=1;weight =2;color=“black”;

}

Now,addadefinitionfortheoverloadedconstructormethod–assigningdefaultvaluestoclassvariableswhenanobjectiscreatedpassingtwoargumentsDog::Dog(int age,int weight ){

this->age=age;this->weight =weight ;color=“white”;

}

Page 233: C++ Programming in easy steps, 5th Edition

Thethis->pointerisusedtoexplicitlyidentifyclassmemberswhenargumentshavethesamenameasmembers.

Inthemainmethod,insertastatementtocreateaDogobjectwithoutpassinganyarguments–callingthedefaultconstructorDogrex;

Addstatementscallingeachgettermethodtoretrievethedefaultvalues–setbythedefaultconstructormethodcout <<“Rexisa“<<rex.getAge();cout <<“yearold“<<rex.getColor();cout <<“dogwhoweighs“<<rex.getWeight ();cout <<“pounds.”;

Now,addacalltotheoverloadedoutputmethodrex.bark(“GRRR!”);

InsertastatementtocreateaDogobjectpassingtwoarguments–tocalltheoverloadedconstructorDogsammy(2,6);

Addstatementstoretrievethevaluessetbytheoverloadedconstructormethodandcalltheoverloadedoutputmethodcout <<“Sammyisa“<<sammy.getAge();cout <<“yearold“<<sammy.getColor();cout <<“dogwhoweighs“<<sammy.getWeight ();cout <<“pounds.”;sammy.bark(“BOWOW!”);

Save,compile,andruntheprogram

Page 234: C++ Programming in easy steps, 5th Edition

Don’taddparenthesesaftertheobjectnamewhencreatinganobjectwithoutpassingarguments–noticeit’sDogrex;notDogrex();

ThisisthefinalrenditionoftheDogclass.Besureyoucanreadilyidentifyitspublicandprivatemembersbeforeproceeding.

Page 235: C++ Programming in easy steps, 5th Edition
Page 236: C++ Programming in easy steps, 5th Edition

InheritingclasspropertiesAC++classcanbecreatedasabrandnewclass,likethoseinpreviousexamples,orcanbe“derived”fromanexistingclass.Importantly,aderivedclassinheritsmembersoftheparent(base)classfromwhichitisderived–inadditiontoitsownmembers.

Theabilitytoinheritmembersfromabaseclassallowsderivedclassestobecreatedthatsharecertaincommonproperties,whichhavebeendefinedinthebaseclass.Forexample,a“Polygon”baseclassmaydefinewidthandheightpropertiesthatarecommontoallpolygons.Classesof“Rectangle”andTriangle”couldbederivedfromthePolygonclass–inheritingwidthandheightproperties,inadditiontotheirownmembersdefiningtheiruniquefeatures.

ThevirtueofinheritanceisextremelypowerfulandisthesecondprincipleofObjectOrientedProgramming(OOP).

Aderivedclassdeclarationaddsacolon:afteritsclassname,followedbyanaccessspecifierandtheclassfromwhichitderives.

derived.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Declareaclassnamed“Polygon”containingtwoprotectedvariables,accessibleonlytomembersofthisclassandclassesderivedfromthisclass,alongwithapublic

Page 237: C++ Programming in easy steps, 5th Edition

methodtoassignvaluestothosevariablesclassPolygon{

protected:int width,height ;

public:voidsetValues(int w,int h){width=w;height =h;}

};

AfterthePolygonclass,declareaRectangleclassthatderivesfromthePolygonclassandaddsauniquemethodclassRectangle:publicPolygon{

public:int area(){return(width*height );}

};

AftertheRectangleclass,declareaTriangleclassthatderivesfromthePolygonclassandaddsauniquemethodclassTriangle:publicPolygon{public:

int area(){return((width*height )/2);}};

AftertheTriangleclass,addamainmethodcontainingafinalreturnstatementandcreatinganinstanceofeachderivedclassint main(){

Rectanglerect ;Trianglet rgl;return0;

}

InsertcallstothemethodinheritedfromthePolygonbaseclass–toinitializetheinheritedvariablesrect .setValues(4,5);t rgl.setValues(4,5);

Outputthevaluereturnedbytheuniquemethodofeachderivedclasscout <<“Rectanglearea:“<<rect .area()<<endl;cout <<“Trianglearea:“<<t rgl.area()<<endl;

Save,compile,andruntheprogramtoseetheoutput

Page 238: C++ Programming in easy steps, 5th Edition

Don’tconfuseclassinstancesandderivedclasses–aninstanceisacopyofaclass,whereasaderivedclassisanewclassthatinheritspropertiesofthebaseclassfromwhichitisderived.

Aclassdeclarationcanderivefrommorethanoneclass.Forexample,classBox:publicA,publicB,publicC{};.

Page 239: C++ Programming in easy steps, 5th Edition
Page 240: C++ Programming in easy steps, 5th Edition

CallingbaseconstructorsAlthoughderivedclassesinheritthemembersoftheirparentbaseclass,theydonotinherititsconstructoranddestructor.However,itshouldbenotedthatthedefaultconstructorofthebaseclassisalwayscalledwhenanewobjectofaderivedclassiscreated–andthebaseclassdestructoriscalledwhentheobjectgetsdestroyed.Thesecallsaremadeinadditiontothosemadetotheconstructoranddestructormethodsofthederivedclass.

Thedefaultconstructorofthebaseclasshasnoarguments–butthatclassmayalsohaveoverloadedconstructorswhichdo.Ifyouprefertocallanoverloadedconstructorofthebaseclasswhenanewobjectofaderivedclassiscreated,youcancreateamatchingoverloadedconstructorinthederivedclass–havingthesamenumberandtypeofarguments.

basecon.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Declareaclassnamed“Parent”,whichwillbeabaseclassclassParent{

//Classmembersgohere.};

BetweenthebracesoftheParentclassdeclaration,insertapublicaccessspecifierandaddadefaultconstructortooutputtext–identifyingwhenithasbeencalledpublic:

Parent (){cout <<“Default Parent const ructorcalled.”;}

Addanoverloadedconstructor,whichtakesasingleintegerargument,andalsooutputsidentifyingtext

Parent (int a){cout <<endl<<

“OverloadedParent const ructorcalled.”;}

AftertheParentclass,declareaderived“Daughter”classclassDaughter:publicParent{

};

Page 241: C++ Programming in easy steps, 5th Edition

Son–Parent–Daughter

IntheDaughterclassdeclaration,insertapublicaccessspecifierandaddadefaultconstructortooutputtext–identifyingwhenithasbeencalledpublic:

Daughter(){cout <<endl<<“DerivedDaughterclassdefault const ructorcalled.”;}

AftertheDaughterclass,declareaderived“Son”classclassSon:publicParent{

};

IntheSonclassdeclaration,insertapublicaccessspecifierandaddanoverloadedconstructorwhichtakesasingleintegerargument,andalsooutputsidentifyingtextpublic:

Son(int a):Parent (a){cout <<endl<<“DerivedSonclassoverloadedconst ructorcalled.”;}

AftertheSonclass,addamainmethodcontainingafinalreturnstatementandcreatinganinstanceofeachderivedclass–callingbaseclassandderivedclassconstructorsint main(){

Daughteremma;Sonandrew(0);return0;

}

Save,compile,andruntheprogramtoseetheoutputfromeachconstructorinturnasitgetscalled

Page 242: C++ Programming in easy steps, 5th Edition

NoticethatthesyntaxintheoverloadedSonclassconstructorpassestheintegerargumenttotheoverloadedbaseclassconstructor.

Eachclassautomaticallyhasanemptydefaultconstructoranddestructor–forexample,Son(){}and~Son(){}.

Page 243: C++ Programming in easy steps, 5th Edition
Page 244: C++ Programming in easy steps, 5th Edition

OverridingbasemethodsAmethodcanbedeclaredinaderivedclasstooverrideamatchingmethodinthebaseclass–ifbothmethoddeclarationshavethesamename,arguments,andreturntype.Thiseffectivelyhidesthebaseclassmethodasitbecomesinaccessibleunlessitiscalledexplicitly,usingthe::scoperesolutionoperatorforpreciseidentification.

Thetechniqueofoverridingbaseclassmethodsmustbeusedwithcare,however,toavoidunintentionallyhidingoverloadedmethods–asingleoverridingmethodinaderivedclasswillhidealloverloadedmethodsofthatnameinthebaseclass!

override.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<st ring>#include<iost ream>usingnamespacestd;

Declareaclassnamed“Man”,whichwillbeabaseclassclassMan{

//Classmembersgohere.};

BetweenthebracesoftheManclassdeclaration,insertapublicaccessspecifierandaninlineoutputmethodpublic:

voidspeak(){cout <<“Hello!”<<endl;}

Now,insertanoverloadedinlineoutputmethodvoidspeak(st ringmsg){cout <<“”<<msg<<endl;}

AftertheManclassdeclaration,declareaclassnamed“Hombre”thatisderivedfromtheManclassclassHombre:publicMan{

//Classmembersgohere.};

Page 245: C++ Programming in easy steps, 5th Edition

Themethoddeclarationinthederivedclassmustexactlymatchthatinthebaseclasstooverrideit–includingtheconstkeywordifitisused.

BetweenthebracesoftheHombreclassdeclaration,insertanaccessspecifierandamethodthatoverridestheoverloadedbaseclassmethod–withoutataboutputpublic:

voidspeak(st ringmsg){cout <<msg<<endl;}

AftertheHombreclassdeclaration,addamainmethodcontainingafinalreturnstatementandcreatingtwoobjects–aninstanceofthebaseclassandaninstanceofthederivedclassint main(){

Manhenry;Hombreenrique;//Addmorestatementshere.return0;

}

Inthemainmethod,insertstatementscallingbothmethodsofthebaseclasshenry.speak();henry.speak(“It ’sabeaut ifulevening.”);

Next,insertastatementcallingtheoverridingmethodinthederivedclass–producingoutputwithoutatabenrique.speak(“Hola!”);

Now,insertastatementexplicitlycallingtheoverriddenmethodinthebaseclassenrique.Man::speak(“Esunatardehermosa.”);

Save,compile,andruntheprogramtoseetheoutputfromtheoverridingandoverriddenmethods

Page 246: C++ Programming in easy steps, 5th Edition

HenryandEnrique

Theoverridingmethoddeclaredinthederivedclasshidesbothoverloadedclassesinthebaseclass.Trycallingenrique.speak()–thecompilerwillcomplainthereisnomatchingmethodforthatcall.

Page 247: C++ Programming in easy steps, 5th Edition
Page 248: C++ Programming in easy steps, 5th Edition

Summary• ThefirstprincipleofObjectOrientedProgrammingistheencapsulationofdataand

functionalitywithinasingleclass.

• Accessspecifierspublic,private,andprotectedcontroltheaccessibilityofclassmembersfromoutsidetheclass.

• Aclassdeclarationdescribesadatastructurefromwhichinstanceobjectscanbecreated.

• Publicsetterandgetterclassmethodsstoreandretrievedatafromprivateclassvariablemembers.

• Thescoperesolutionoperator::canexplicitlyidentifyaclass.

• Classmembersthathavethesamenameasapassedargumentcanbeexplicitlyidentifiedbythethis->pointer.

• Aconstructormethodiscalledwhenanobjectgetscreatedandadestructormethodiscalledwhenitgetsdestroyed.

• Classvariablescanbeautomaticallyinitializedbyaconstructor.

• Classmethodscanbeoverloadedlikeotherfunctions.

• ThesecondprincipleofObjectOrientedProgrammingisthevirtueofinheritancethatallowsderivedclassestoinheritthepropertiesoftheirparentbaseclass.

• Inaderivedclassdeclaration,theclassnameisfollowedbya:coloncharacter,anaccessspecifier,anditsbaseclassname.

• Whenaninstanceobjectofaderivedclassiscreated,thedefaultconstructorofthebaseclassgetscalledinadditiontotheconstructorofthederivedclass.

• Aderivedclassmethodcanoverrideamatchingmethodinitsbaseclass–alsooverridingalloverloadedmethodsofthatnamewithinthebaseclass.

Page 249: C++ Programming in easy steps, 5th Edition

8

Harnessingpolymorphism

Thischapterdemonstrateshowtoseparateprogramsintomodularcomponentsandintroducesthetopicofpolymorphism

–thethirdprincipleofC++ObjectOrientedProgramming.

PointingtoclassesCallingavirtualmethodDirectingmethodcallsProvidingcapabilityclassesMakingabstractdatatypesBuildingcomplexhierarchiesIsolatingclassstructuresEmployingisolatedclassesSummary

Page 250: C++ Programming in easy steps, 5th Edition
Page 251: C++ Programming in easy steps, 5th Edition

PointingtoclassesThethreecornerstonesofObjectOrientedProgramming(OOP)areencapsulation,inheritance,andpolymorphism.ExamplesinthepreviouschapterhavedemonstratedhowdatacanbeencapsulatedwithinaC++class,andhowderivedclassesinheritthepropertiesoftheirbaseclass.Thischapterintroducesthefinalcornerstoneprincipleofpolymorphism.

Theterm“polymorphism”(fromGreek,meaning“manyforms”)describestheabilitytoassignadifferentmeaning,orpurpose,toanentityaccordingtoitscontext.

InC++,overloadedoperatorscanbedescribedaspolymorphic.Forexample,the*charactercanrepresenteitherthemultiplyoperatororthedereferenceoperator,accordingtoitscontext.Similarly,the+charactercanrepresenteithertheaddoperatorortheconcatenateoperator,accordingtoitscontext.

Moreimportantly,C++classmethodscanalsobepolymorphic.Thekeytounderstandingpolymorphismwithclassesistorecognizethatabaseclasspointercanbecreatedthatisalsoboundtoaparticularderivedclassbyassociation.

Apointertoabaseclasscanbeassignedthememoryaddressofaderivedclasstoprovidea“context”–touniquelyidentifythatderivedclass.Forexample,withaBasebaseclassandaderivedSubclass,apointercanbecreatedlikethis:

Subinst ;Base*pSub=&inst ;

ormoresimplyusingthenewkeyword,likethis:

Base*pSub=newSub;

TurnbacktoChapterSixformoreonpointers.

Wheretherearemultiplederivedclasses,baseclasspointerscanbecreatedbindingeachderivedclassbyitsuniquememoryaddress–whichcanberevealedusingtheaddressof&operator.

Page 252: C++ Programming in easy steps, 5th Edition

classptr.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

DeclareaBaseclasscontainingamethodtooutputapassedintegervalueinhexadecimalformatclassBase{

public:voidIdent ify(int adr)const{cout <<“Baseclasscalledby0x”<<hex<<adr<<endl;}

};

Declaretwoemptyderivedclasses,SubAandSubBclassSubA:publicBase{};classSubB:publicBase{};

Declareamainmethodcontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainmethod,insertstatementstocreatetwobaseclasspointers–eachbindingtoaspecificderivedclassBase*pt rA=newSubA;Base*pt rB=newSubB;

Now,insertstatementsthatusethepointerstocallthebaseclassmethod,passingthememoryaddressofeachforoutputpt rA->Ident ify((int )&pt rA);pt rB->Ident ify((int )&pt rB);

Save,compile,andruntheprogramtoseetheaddresses

Page 253: C++ Programming in easy steps, 5th Edition

The->classpointeroperatorisusedheretocallclassmethods.

Thehexadecimaladdressispassedasanintdatatype,thendisplayedinhexadecimalformatbythehexoutputmanipulator.Theaddresseswillbedifferenteachtimetheprogramexecutes–theyareassigneddynamically.

Page 254: C++ Programming in easy steps, 5th Edition
Page 255: C++ Programming in easy steps, 5th Edition

CallingavirtualmethodAbaseclasspointerthatisboundtoaspecificderivedclasscanbeusedtocallderivedclassmethodsthathavebeeninheritedfromthebaseclass.Methodsthatareuniquetothederivedclassmust,however,becalledviaaninstanceobject.

Abaseclasspointerthatisboundtoaspecificderivedclasscanalsobeusedtoexplicitlycallamethodinthebaseclassusingthe::scoperesolutionoperator.

Mostusefully,aninheritedmethodinaderivedclasscanoverridethatinthebaseclasswhenthebasemethodhasbeendeclaredasa“virtual”method.Thisisjustaregularmethoddeclarationinthebaseclassprecededbythevirtualkeyword.Thedeclarationofavirtualmethodindicatesthattheclasswillbeusedasabaseclassfromwhichanotherclasswillbederived,whichmaycontainamethodtooverridethevirtualbasemethod.

virtual.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Declareabaseclassnamed“Parent”,containingaregularmethoddeclarationandavirtualmethoddeclarationclassParent{

public:voidCommon()const{cout <<“Iampart ofthisfamily,“;}

virtualvoidIdent ify()const{cout <<“Iamtheparent”<<endl;}

};

Declareaderivedclassnamed“Child”,containingamethodtooverridethevirtualbasemethodclassChild:publicParent{

public:voidIdent ify()const{cout <<“Iamthechild”<<endl;}

};

Page 256: C++ Programming in easy steps, 5th Edition

Pointerstoabaseclasscannotbeusedtocallnon-inheritedmethodsinaderivedclass.

Declarea“Grandchild”class,derivedfromthe“Child”class,containingamethodtooverridethevirtualbasemethodandaregularmethoddeclarationclassGrandchild:publicChild{

public:voidIdent ify()const{cout <<“Iamthegrandchild”<<endl;}

voidRelate()const{cout <<“Grandchildhasparent andgrandparent”;}

};

ParentandChildandGrandchild

Declareamainmethodcontainingafinalreturnstatementandcreatinginstancesofeachderivedclass,plusbaseclasspointersbindingthosederivedclassesint main(){

Childson;Grandchildgrandson;Parent *pt rChild=&son;Parent *pt rGrandchild=&grandson;//Addmorestatementshere.return0;

}

Inthemainmethod,insertcallstoeachmethodpt rChild->Common();//Inherited.pt rChild->Ident ify();//Overriding.pt rGrandchild->Common();//Inherited.pt rGrandchild->Ident ify();//Overriding.pt rChild->Parent ::Common();//Explicit .pt rChild->Parent ::Ident ify();//Explicit .grandson.Relate();//Viainstance.

Page 257: C++ Programming in easy steps, 5th Edition

Save,compile,andruntheprogramtoseetheoutput

Here,theGrandchildclassinheritsthepropertiesoftheChildclass,whichinheritsthepropertiesoftheParentclass.

Page 258: C++ Programming in easy steps, 5th Edition
Page 259: C++ Programming in easy steps, 5th Edition

DirectingmethodcallsThegreatadvantageofpolymorphismwithmultiplederivedclassobjectsisthatcallstomethodsofthesamenamearedirectedtotheappropriateoverridingmethod.

Abaseclassmaycontainonlyvirtualmethodswhicheachderivedclassmayoverridewiththeirownmethods,butbaseclassmethodscanstillbecalledexplicitlyusingthe::scoperesolutionoperator.Thiscanallowinconsistencies,however–thisexamplewouldseemtoimplythatchickenscanfly!

birds.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Declareabaseclassnamed“Bird”,containingtwovirtualmethoddeclarationsclassBird{

public:virtualvoidTalk()const{cout <<“Abirdtalks...”<<endl;}

virtualvoidFly()const{cout <<“Abirdflies...”<<endl;}

};

Declareaderivedclassnamed“Pigeon”,containingtwomethodstooverridethoseinthebaseclassclassPigeon:publicBird{

public:voidTalk()const{cout <<“Coo!Coo!”<<endl;}

voidFly()const{cout <<“Apigeonfliesaway...”<<endl;}

};

Page 260: C++ Programming in easy steps, 5th Edition

Overridingmethodsinderivedclassmay,optionally,includethevirtualprefix–asareminderitisoverridingabaseclassmethod.

Declareaderivedclassnamed“Chicken”,containingtwomethodstooverridethoseinthebaseclassclassChicken:publicBird{

public:voidTalk()const{cout <<“Cluck!Cluck!”<<endl;}

voidFly()const{cout <<“I\’mjust achicken–Ican\’t fly!”<<endl;}

};

Declareamainmethodcontainingafinalreturnstatementandcreatingbaseclasspointersbindingderivedclassesint main(){

Bird*pPigeon=newPigeon;Bird*pChicken=newChicken;//Addmorestatementshere.return0;

}

Inthemainmethod,insertcallstoeachmethodpPigeon->Talk();pPigeon->Fly();pChicken->Talk();pChicken->Fly();pPigeon->Bird::Talk();pChicken->Bird::Fly();//Inappropriatecall.

Save,compile,andruntheprogramtoseetheoutput

Page 261: C++ Programming in easy steps, 5th Edition

Thebackslash\characterisrequiredtoescapetheapostropheinstrings.

Page 262: C++ Programming in easy steps, 5th Edition
Page 263: C++ Programming in easy steps, 5th Edition

ProvidingcapabilityclassesClasseswhosesolepurposeistoallowotherclassestobederivedfromthemareknownas“capabilityclasses”–theyprovidecapabilitiestothederivedclasses.

Capabilityclassesgenerallycontainnodata,butmerelydeclareanumberofvirtualmethodsthatcanbeoverriddenintheirderivedclasses.

Thefollowingexamplebuildsuponthepreviousexampletodemonstratehowthe“Bird”classcanbebetterwrittenasacapabilityclass.Itsmethodsnolongercontainoutputstatements,butreturna-1(error)valueiftheyarecalledexplicitly.

Itisnecessarytochangethereturntypeofthosemethodsfromvoidtoint andthesechangesmustalsobereflectedineachoverridingmethodinthederivedclasses.

capability.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Declareabasecapabilityclassnamed“Bird”,containingtwovirtualmethoddeclarationsthatwillsignalanerrorifcalledexplicitlyclassBird{

public:virtualint Talk()const {return-1;}virtualint Fly()const {return-1;}

};

Declareaderivedclassnamed“Pigeon”,containingtwomethodstooverridethoseinthebaseclassclassPigeon:publicBird{

public:int Talk()const{cout <<“Coo!Coo!”<<endl;return0;}

int Fly()const{cout <<“Apigeonfliesaway...”<<endl;return0;}

};

Page 264: C++ Programming in easy steps, 5th Edition

Thereturnvalueofoverridingmethodsinderivedclassesmustmatchthosedeclaredinthebaseclass.

Declareaderivedclassnamed“Chicken”containingtwomethodstooverridethoseinthebaseclassclassChicken:publicBird{

public:int Talk()const{cout <<“Cluck!Cluck!”<<endl;return0;}

int Fly()const{cout <<“I\’mjust achicken–Ican\’t fly!”<<endl;return0;}

};

Declareamainmethodcreatingbaseclasspointersbindingthederivedclassesint main(){

Bird*pPigeon=newPigeon;Bird*pChicken=newChicken;

}

Inthemainmethod,insertmethodcallsandastatementtoterminatetheprogramwhenanerrorismetbyexplicitlycallingabaseclassmethodpPigeon->Talk();pChicken->Talk();

pPigeon->Bird::Talk();if(-1){cout <<“Error!-Programended.”

<<endl;return0;}

pPigeon->Fly();//Callwillnot bemade.pChicken->Fly();//Callwillnot bemade.return0;//Statement willnot beexecuted

Save,compile,andruntheprogramtoseetheoutput

Page 265: C++ Programming in easy steps, 5th Edition

Capabilityclassmethodsareintendedtobeoverriddeninderivedclasses–theyshouldnotbecalledexplicitly.

Referbacktohereformoredetailsonerrorhandling.

Page 266: C++ Programming in easy steps, 5th Edition
Page 267: C++ Programming in easy steps, 5th Edition

MakingabstractdatatypesAnAbstractDataType(ADT)representsaconcept,ratherthanatangibleobject,andisalwaysthebasetootherclasses.AbaseclasscanbemadeintoanADTbyinitializingoneormoreofitsmethodswithzero.Theseareknownas“purevirtualmethods”andmustalwaysbeoverriddeninderivedclasses.

adt.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

DeclareabaseADTclassnamed“Shape”,containingthreepurevirtualmethodsclassShape{

public:virtualint getArea()=0;virtualint getEdge()=0;virtualvoidDraw()=0;

};

Declareaderivedclassnamed“Rect”,containingtwoprivatevariablesclassRect :publicShape{

private:int height ,width;

};

Inthederivedclassdeclaration,insertapublicconstructoranddestructorpublic:

Rect (int initWidth,int initHeight ){height =initHeight ;width=initWidth;

}

~Rect ();

Page 268: C++ Programming in easy steps, 5th Edition

ItisillegaltocreateaninstanceobjectofanADT–attemptingtodosowillsimplycreateacompilererror.

Inthederived“Rect”classdeclaration,declarethreepublicmethodstooverridethepurevirtualmethodsdeclaredinthe“Shape”baseclassint getArea(){returnheight *width};int getEdge(){return(2*height )+(2*width);}

voidDraw(){

for(int i=0;i<height ;i++){for(int j=0;j<width;j++){cout <<“x”;}

cout <<endl;}}

Declareamainmethodcontainingafinalreturnstatementandcreatingtwoinstancesofthederived“Rect”class–torepresentaSquareandaQuadrilateralshapeint main{

Shape*pQuad=newRect (3,7);Shape*pSquare=newRect (5,5);//Addmorestatementshere.return0;

}

Inthemainmethod,insertcallstoeachmethodthensave,compile,andruntheprogramtoseetheoutputpQuad->Draw();cout <<“Areais”<<pQuad->getArea()<<endl;cout <<“Perimeteris”<<pQuad->getEdge()<<endl;

pSquare->Draw();cout <<“Areais”<<pSquare->getArea()<<endl;cout <<“Perimeteris”<<pSquare->getEdge()<<endl;

Page 269: C++ Programming in easy steps, 5th Edition

AbaseclassneedonlycontainonepurevirtualmethodtocreateanAbstractDataType.

Page 270: C++ Programming in easy steps, 5th Edition
Page 271: C++ Programming in easy steps, 5th Edition

BuildingcomplexhierarchiesItissometimesdesirabletoderiveanADTfromanotherADTtoconstructacomplexhierarchyofclasses.Thisprovidesgreatflexibilityandisperfectlyacceptable,providingeachpuremethodisdefinedatsomepointinaderivedclass.

hierarchy.cpp

StartanewprogrambyspecifyingtheC++libraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

DeclareabaseADTclassnamed“Boat”,containingavariableandaccessormethodtogetherwithonepurevirtualmethodclassBoat{

protected:int length;

public:int getLength(){returnlength;}virtualvoidModel()=0;

};

DeclareanADTclass(derivedfromtheBoatclass)named“Sailboat”–alsocontainingavariableandaccessormethodtogetherwithonepurevirtualmethodclassSailboat :publicBoat{

protected:int mast ;

public:int getMast (){returnmast ;}virtualvoidBoom()=0;

};

Declarearegularclass(derivedfromtheSailboatclass)named“Laser”,inwhichallmemberswillallowpublicaccessclassLaser:publicSailboat{

public:

};

Page 272: C++ Programming in easy steps, 5th Edition

TheBoatclasshaspropertiescommontoanyboat,whereastheSailboatclasshaspropertiesspecifictoboatsthathavesails.

IntheLaserclass,insertacalltoitsconstructormethodtoassignvaluestothevariablesineachclassfromwhichthisclassisderived–andcallthedestructormethodLaser(){mast =19;length=35;}~Laser();

IntheLaserclass,definethepurevirtualmethodsdeclaredineachclassfromwhichthisclassisderivedvoidModel(){cout <<“LaserClassic”<<endl;}voidBoom(){cout <<“Boom:14ft ”<<endl;}

Declareamainmethodcontainingafinalreturnstatementandcreatinganinstanceofthederivedclassonthebottomtierofthehierarchyint main(){

Laser*pLaser=newLaser;//Addmorestatementshere.return0;

}

Inthemainmethod,insertcallstoeachdefinedmethodpLaser->Model();cout <<“Length:“<<

pLaser->getLength()<<“ft ”<<endl;cout <<“Height :“<<

pLaser->getMast ()<<“ft ”<<endl;pLaser->Boom();

Save,compile,andruntheprogramtoseetheoutput

Page 273: C++ Programming in easy steps, 5th Edition

TryaddingaPowerboatclassderivedfromtheBoatclass(tocontainengineinformation),andaCruiserclassderivedfromthePowerboatclass–toassignvariablevaluesandtodefinevirtualmethods.

Page 274: C++ Programming in easy steps, 5th Edition
Page 275: C++ Programming in easy steps, 5th Edition

IsolatingclassstructuresThesourcecodeforeachexampleprograminthisbookisgenerallycontainedinasingle.cppfiletosavespace,butinrealityOOPprogramsareoftencontainedinthreeseparatefiles:

• Header.hfile–containsonlyclassdeclarations.s

• Implementation.cppfile–containsclassdefinitionstoimplementthemethodsdeclaredintheheaderfile,whichisreferencedbyan#includedirective.

• Client.cppfile–containsamainmethodthatemploystheclassmembersdeclaredintheheaderfile,whichisalsoreferencedbyan#includedirective.

Theclientfileissometimesreferredtoasa“driver”file.

Forexample,asumcalculatorprogrammightcomprisethreefilesnamedops.h(aheaderfiledeclaringoperationclasses),ops.cpp(animplementationfiledefiningtheoperationmethods),andsum.cpp(aclientfilecallingthevariousoperations).

Whencompilingsum.cpp,thecompilerincorporatestheincludedheaderfileandimplementationfileintotheprogram.Itfirsttranslatestheheaderfileandimplementationfileintoabinaryobjectfile(ops.o),thenittranslatestheheaderfileandclientfileintoasecondbinaryobjectfile(sum.o).Finally,theLinkercombinesbothobjectfilesintoasingleexecutablefile(sum.exe).

Page 276: C++ Programming in easy steps, 5th Edition

Usingan#includedirectivetoreferenceaheaderfileworksinasimilarmannertousingan#includedirectivetoreferenceastandardC++library.

Isolatingclassstructuresinseparate“modular”fileshastheadvantageofimprovingportability,andmakescodemaintenanceeasierbyclearlyidentifyingthepurposeofeachfile.

Tohavethecompilercombineallthreesourcecodefilesintoasingle,executablefileitisonlynecessarytoexplicitlyspecifythe.cppfilesinthecompilercommand–an#includedirectiveensurestheheaderfilewillalsoberecognized.

Forexample,withthestatement#include“ops.h”inbothops.cppandsum.cppthecommandtocompiletheexampledescribedbelowneednotspecifytheops.hheaderinthecompilercommand,butisjustc++ops.cppsum.cpp-osum.exe.

Calculator

Thisexamplewillallowtheusertoinputasimplearithmeticalexpressionandoutputthecalculatedresult.Itwillprovideinstructionswhenfirstlaunchedandallowtheusertomakesubsequentexpressions–orexitbyenteringazerocharacter.

ops.h

Startaheaderfilebydeclaringaclassnamed“Calculator”classCalculator{

};

Intheclassdeclaration,insertpublicmethoddeclarationspublic:

Calculator();//(Const ructor)Toset init ialstatus.voidlaunch();//Todisplayinit ialinst ruct ions.voidreadInput ();//Toget expression.voidwriteOutput ();//Todisplayresult .boolrun();//(Accessor)Toget current status.

Intheclassdeclaration,insertprivatevariabledeclarationsprivate:

doublenum1,num2;//Tostoreinput numbers.

Page 277: C++ Programming in easy steps, 5th Edition

charoper;//Tostoreinput operator.boolstatus;//Tostorecurrent status.

Savetheheaderfileas“ops.h”

Turntothenextpagetocontinuethisexamplebycreatinganimplementationfile–containingdefinitionsfortheCalculatorclassmethodsdeclaredinthe“ops.h”headerfile

Noticethattheheaderfilenamemustbesurroundedbyquotesinan#includedirective–notbythe<>angledbracketsusedtoincludeastandardC++library.

Page 278: C++ Programming in easy steps, 5th Edition
Page 279: C++ Programming in easy steps, 5th Edition

Employingisolatedclasses

ops.cpp

Startanimplementationfilewithincludedirectivesfortheheaderfilecreatedhere,andthestandardC++librarysupportinginput/outputstatements#include“ops.h”//Referenceheaderfile.# include<iost ream>usingnamespacestd;

Addthefollowingdefinitionsforeachmethodintheheaderfile,thensavetheimplementationfileas“ops.cpp”Calculator::Calculator(){status=t rue;}//Init ializestatus.

voidCalculator::launch()//Displayinst ruct ions.{

cout <<endl<<“***SUMCALCULATOR***”<<endl;cout <<“Enteranumber,anoperator(+,-,*,/),and

anothernumber.”<<endl<<“Hit Returntocalculate.Enterzerotoexit .”<<endl;

}

voidCalculator::readInput ()//Get expression.{

cout <<“>“;cin>>num1;//Get 1st number.if(num1==0)status=false;//Exit ifit ’szero.else{cin>>oper;cin>>num2;}//Orget therest .

}

voidCalculator::writeOutput ()//Displayresult .{

if(status)switch(oper)//Ifcont inuing.{//Showresult .case‘+’:{cout <<(num1+num2)<<endl;break;}case‘-’:{cout <<(num1-num2)<<endl;break;}case‘*’:{cout <<(num1*num2)<<endl;break;}case‘/’:if(num2!=0)

cout <<(num1/num2)<<endl;elsecout <<“Cannot dividebyzero”<<endl;

}}

boolCalculator::run()//Get thecurrent status.{returnstatus;}

Page 280: C++ Programming in easy steps, 5th Edition

Duetospacelimitation,thisprogrammakesbarelynoattemptatinputvalidation–itassumestheuserwillenteravalidexpression,suchas8*3.

sum.cpp

Startaclientfilewithanincludedirectivetoincorporatetheheaderfilecreatedhere#include“ops.h”

Declareamainmethodcontainingafinalreturnstatement,andcreatingapointerplusacalltodisplayinstructionsint main(){

Calculator*pCalc=newCalculator;pCalc->launch();//Addmorestatementshere.return0;

}

Inthemainmethod,insertalooptoreadexpressionsandwriteresultswhiletheprogramstatuspermitswhile(pCalc->run()){

pCalc->readInput ();pCalc->writeOutput ();

}

Savetheclientfileas“sum.cpp”,alongside“ops.h”and“ops.cpp”,thencompiletheprogramwiththiscommandc++ops.cppsum.cpp-osum.exe

Runtheprogramandentersimpleexpressionstoseetheresults,thenenterzeroandhitReturntoexittheprogram

Page 281: C++ Programming in easy steps, 5th Edition

ThisprogramloopsuntiltheusertypesazeroandhitsReturn–changingthe“status”controlvariabletofalse,andsoexitingtheprogram.

Page 282: C++ Programming in easy steps, 5th Edition
Page 283: C++ Programming in easy steps, 5th Edition

Summary• ThethreecornerstonesofObjectOrientedProgrammingareencapsulation,inheritance,

andpolymorphism.

• Polymorphicentitieshaveadifferentmeaning,orpurpose,accordingtotheircontext.

• Abaseclasspointercanbeusedtocallinheritedmethodsinthederivedclasstowhichitisbound.

• Abaseclasspointercanalsobeusedtoexplicitlycallbaseclassmethodsusingthe::scoperesolutionoperator.

• Virtualbaseclassmethodsareintendedtobeoverriddeninderivedclasses.

• Polymorphismallowscallstomethodsofthesamenametobedirectedtotheappropriateoverridingmethod.

• Capabilityclassesgenerallycontainnodata,butmerelydeclarevirtualmethodsthatcanbeoverriddeninderivedclasses.

• Virtualmethodsthatreturna-1valuesignalanerrortoindicatetheyshouldnotbecalleddirectly.

• AnAbstractDataTyperepresentsaconcept,andisalwaysthebasetootherclasses.

• Declarationofapurevirtualmethod,withtheassignation=0,indicatesthatclassisanADT.

• ClassescanbederivedfromanADT–butyoucannotcreateaninstanceofanADT.

• AnADTcanbederivedfromanotherADTtocreateacomplexhierarchyofclasses.

• Programscanbeseparatedintoheader,implementation,andclientfilestoaidportabilityandtoeasecodemaintenance.

• Headerfilesthatarereferencedby#includedirectiveswillbeautomaticallyincludedbythecompilerduringcompilation.

Page 284: C++ Programming in easy steps, 5th Edition

9

Processingmacros

ThischapterdemonstrateshowtheC++compilercanbemadetoperformusefultasksbeforecompilingaprogram.

ExploringcompilationDefiningsubstitutesDefiningconditionsProvidingalternativesGuardinginclusionsUsingmacrofunctionsBuildingstringsDebuggingassertionsSummary

Page 285: C++ Programming in easy steps, 5th Edition
Page 286: C++ Programming in easy steps, 5th Edition

ExploringcompilationWhenevertheC++compilerruns,itfirstcallsuponitspreprocessortoseekanycompilerdirectivesthatmaybeincludedinthesourcecode.Eachofthesebeginwiththe# hashcharacterandwillbeimplementedfirsttoeffectivelymodifythesourcecodebeforeitisassembledandcompiled.

Thechangesmadebycompilerdirectivestothepreprocessorcreatenewtemporaryfilesthatarenotnormallyseen.Itisthesetemporaryfilesthatareusedtocreateabinaryobjectfile:

• Thefirsttemporaryfilecreatedduringcompilationexpandstheoriginalsourcecodebyreplacingitscompilerdirectiveswithlibrarycodethatimplementsthosedirectives.Thistextfileisnamedlikethesourcefile,butwitha.iifileextension.

• Thesecondtemporaryfilecreatedduringcompilationisatranslationofthetemporaryexpanded.iifileintolow-levelAssemblylanguageinstructions.Thistextfileisnamedlikethesourcefile,butwitha.sfileextension.

• ThethirdtemporaryfilecreatedduringcompilationisatranslationofthetemporaryAssemblylanguage.sfileintomachinecode.Thisbinaryobjectfileisnamedlikethesourcefile,butwitha.ofileextension.

So,thecompilationprocessemploysthePreprocessortocompilesourcecode,an“Assembler”totranslatethisintomachinecode,andaLinkertoconvertoneormorebinary

Page 287: C++ Programming in easy steps, 5th Edition

objectsintoanexecutableprogram.

Youcanseethetemporaryfilesbyinstructingthecompilertosavethemusingthe-save-tempscompileroption.Bothtemporarytextfilescanthenbeexaminedbyopeningtheminaplaintexteditor.

Mostsignificantly,youcanseethatthetemporaryfilewiththe.iifileextensioncontainsthecompletefunctiondefinitionsfromanyincludedlibrary.Forexample,itreplacesan#include<iost ream>directivewithdefinitionsforthecin,cout ,cerrfunctions,andtheclogfunctionthatcanbeusedtoredirecterrormessagestoafile.Theendofthe.iifileshowsthedefinedfunctionstobepartofthe“std”namespace–sotheycanappearwithoutthestd::prefix.

prog.cpp

Createasimpleprogramnamed“prog.cpp”thatwilloutputamessagewhenitgetsexecuted#include<iost ream>usingnamespacestd;int main(){

cout <<“Thisisasimpletest program”<<endl;return0;

}

Issueacommandusingthe-save-tempsoption,tosavetemporaryfiles,anda-coptiontocompilethisprogram’ssourcefilesintoanobjectfile–withnoexecutablefilec++prog.cpp-save-temps-c

Openthe.iifileinaplaintexteditorsuchasNotepad,thenscrolltotheendofthefiletoseethemodifiedsourcecode–noticehowthe<iost ream>libraryfunctionsaredefinedinthestdnamespace

Openthe.sfileinaplaintexteditortoseethelow-levelassemblerinstructions–noticehowthemessagestringisnowterminatedbythespecial\0character

Issueacommandtooutputanexecutablefilefromthe.oobjectfile,thenrunthe

Page 288: C++ Programming in easy steps, 5th Edition

programtoseethemessagec++prog.o-oprog.exe

Oneormoreobjectfilescanbeusedtocreateanexecutablefile–asdescribedhere.

Youcancombinethesesteps,creatinganexecutablefileandsavingtemporaryfiles,byissuingthecommandc++prog.cpp-save-temps-oprog.exe.

Page 289: C++ Programming in easy steps, 5th Edition
Page 290: C++ Programming in easy steps, 5th Edition

DefiningsubstitutesJustasthepreprocessorsubstituteslibrarycodefor#includedirectives,otherpreprocessordirectivescanbeusedtosubstitutetextornumericvaluesbeforeassemblyandcompilation.

The#definedirectivespecifiesamacro,comprisinganidentifiernameandastringornumericvalue,tobesubstitutedbythepreprocessorforeachoccurrenceofthatmacrointhesourcecode.

Like#includepreprocessordirectives,#definedirectivescanappearatthestartofthesourcecode.Aswithconstantvariablenames,themacronametraditionallyusesuppercase,anddefinedstringvaluesshouldbeenclosedwithindoublequotes.Fornumericsubstitutionsinexpressionsthemacronameshouldbeenclosedinparenthesestoensurecorrectprecedence.

define.cpp

Startanewprogrambydeclaringthreedefinedirectives#defineBOOK“C++Programmingineasysteps”#defineNUM200#defineRULE“*******************************”

Specifythelibraryclassestoinclude,andthenamespace#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementandthreestatementstooutputsubstitutedvaluesint main(){

cout <<RULE<<endl<<BOOK<<endl<<RULE;cout <<endl<<“NUMis:”<<NUM<<endl;cout <<“DoubleNUM:”<<((NUM)*2)<<endl;return0;

}

Save,compile,andruntheprogramtoseetheoutput

Page 291: C++ Programming in easy steps, 5th Edition

Numericconstantsareoftenbestdeclaredasconst variables–becausevaluessubstitutedbythepreprocessorarenotsubjecttotype-checking.

Recompiletheprogramsavingthetemporaryfilesc++define.cpp-save-temps-odefine.exe

Openthetemporary“define.ii”fileinaplaintexteditorandscrolltotheendofthefiletoseethesubstitutions

Linuxuserscanemployescapeddoublequotes\””string”\”orplainsinglequotes‘“string”’toencloseaquotedstringinacommand.

Substitutionscanalternativelybemadefromthecommand-lineusinga-Dnameoptiontoreplacemacroswithspecifiedvalues.Notethatstringvalueswithindouble-quotesmustalsobeenclosedinescapedquotesinthecommand–sothesubstitutionwillincludethedouble-quotecharacters.

Page 292: C++ Programming in easy steps, 5th Edition

Delete,orcomment-out,thedefinedirectivesforboththeBOOKandNUMidentifiers–thensavetheprogramfiletoapplythechanges

Recompiletheprogram,specifyingsubstitutemacrovalues,thenruntheprogramoncemorec++-DNUM=50-DBOOK=\””XMLineasysteps”\”define.cpp-odefine.exe

Attemptingtocompileaprograminwhichanidentifierhasnotbeendefinedwillproducea“notdeclaredinthisscope”error.

Page 293: C++ Programming in easy steps, 5th Edition
Page 294: C++ Programming in easy steps, 5th Edition

DefiningconditionsThepreprocessorcanmakeintelligentinsertionstoprogramsourcecodebyusingmacrofunctionstoperformconditionaltests.An#ifdefdirectiveperformsthemostcommonpreprocessorfunctionbytestingtoseeifaspecifiedmacrohasbeendefined.Whenthemacrohasbeendefined,sothetestreturnstrue,thepreprocessorwillinsertalldirectives,orstatements,onsubsequentlinesuptoacorresponding#endifdirective.

Conversely,an#ifndefdirectiveteststoseeifaspecifiedmacrohasnotbeendefined.Whenthattestreturnstrue,itwillinsertalldirectives,orstatements,onsubsequentlinesuptoacorresponding#endifdirective.

Tosatisfyeitherconditionaltest,itshouldbenotedthata#definedirectiveneedonlyspecifythemacronametodefinetheidentifier–itneednotspecifyavaluetosubstitute.

Anypreviouslydefinedmacrocanberemovedlaterusingthe#undefdirective–sothatsubsequent#ifdefconditionaltestsfail.Themacrocanthenberedefinedbyafurther#definedirective:

ifdef.cpp

Startanewprogramwithaconditionaltesttoinsertadirectivewhenamacroisnotalreadydefined#ifndefBOOK

#defineBOOK“C++Programmingineasysteps”#endif

Specifythelibraryclassestoinclude,andthenamespace#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Inthemainfunction,addaconditionalpreprocessortesttoinsertanoutputstatementwhenthetestsucceeds#ifdefBOOK

cout <<BOOK;#endif

Page 295: C++ Programming in easy steps, 5th Edition

Addanotherconditionalpreprocessortesttobothdefineanewmacroandinsertanoutputstatementwhenthetestsucceeds#ifndefAUTHOR

#defineAUTHOR“MikeMcGrath”cout <<“by”<<AUTHOR<<endl;

#endif

Next,addaconditionaltesttoundefineamacroifithasalreadybeendefined#ifdefBOOK

#undefBOOK#endif

Now,addaconditionaltesttoredefineamacroifitisnolongerdefined,andtoinsertanoutputstatement#ifndefBOOK

#defineBOOK“Linuxineasysteps”cout <<BOOK“by“<<AUTHOR<<endl;

#endif

Save,compile,andruntheprogramtoseetheinsertions

Recompiletheprogram,thistimedefiningtheBOOKmacrointhecommand,thenruntheprogramagaintoseethespecifiedvalueappearinthefirstlineofoutputc++-DBOOK=\”“Javaineasysteps”\”ifdef.cpp-oifdef.exe

Eachpreprocessordirectivemustappearonitsownline–youcannotputmultipledirectivesonthesameline.

Page 296: C++ Programming in easy steps, 5th Edition

OnWindowssystems,stringmacrovaluesspecifiedinacommandmustbeenclosedinescapeddoublequotes.

Page 297: C++ Programming in easy steps, 5th Edition
Page 298: C++ Programming in easy steps, 5th Edition

ProvidingalternativesTheconditionaltestperformedby#ifdefand#ifndefcanbeextendedtoprovideanalternativebyaddingan#elsedirective.Forexample:

#ifdefWEATHERcout <<WEATHER;

#else#defineWEATHER“Sunny”

#endif

Similarly,#if,#else,and#elifmacroscanperformmultipleconditionaltests,muchliketheregularC++ifandelsekeywords.

Fortestingmultipledefinitions,the#ifdefmacrocanbeexpressedas#ifdefined,andfurthertestsmadeby#elifdefinedmacros.

The#elifmacrosimplycombineselseandiftoofferanalternativetest.

Whilemostmacrosaredefinedinthesourcefilewitha#definedirective,oronthecommandlinewiththe-Doption,somemacrosareautomaticallypredefinedbythecompiler.Typically,thesehavenamesbeginningwithadoubleunderscoretoavoidaccidentalconfusionwithchosennames.Thecompiler ’spredefinedmacrosareplatform-specific,soaprogramcanemployamultipledefinitiontesttoidentifythehostplatform:

else.cpp

Launchaplaintexteditorandsaveanewfile(withoutanycontent)as“empty.txt”inyourprogram’sdirectory

Toseealistofthecompiler ’spredefinedmacros,issueacommandcallingthecpppreprocessordirectlywitha“-dM”optionontheemptyfilecpp-dMempty.txt

Scrollthroughthelisttofindthe“_WIN32”macroonWindowsorthe“_linux”macroonLinuxsystems

Page 299: C++ Programming in easy steps, 5th Edition

Usethecppcommandtocallthepreprocessordirectly(notthec++command)andensurethe-dMoptioniscapitalizedcorrectly.

Startanewprogramwithaconditionaltesttoseekthe_WIN32and_linuxmacros–toidentifytheplatform#ifdefined__WIN32

#definePLATFORM“Windows”#elifdefined__linux

#definePLATFORM“Linux”#endif

Specifythelibraryclassestoinclude,andthenamespace#include<iost ream>usingnamespacestd;

Now,addamainfunctioncontainingafinalreturnstatementandastatementtoidentifythehostplatformint main(){

cout <<PLATFORM<<“System”<<endl;return0;

}

Inthemainfunction,insertstatementstoexecuteforspecificplatformsif(PLATFORM==“Windows”)

cout <<“PerformingWindows-onlytasks...”<<endl;if(PLATFORM==“Linux”)

cout <<“PerformingLinux-onlytasks...”<<endl;

Save,compile,andruntheprogramtoseeplatform-specificoutput

Page 300: C++ Programming in easy steps, 5th Edition

Thepredefined_WIN32macrohasoneunderscorebutthe__linuxmacrohastwounderscorecharacters.

Theconditionaltestofpredefinedmacroscouldbeextendedtoseekthoseofotheroperatingsystems,andafinal#elsedirectiveaddedtospecifyan“Unknown”default.

Page 301: C++ Programming in easy steps, 5th Edition
Page 302: C++ Programming in easy steps, 5th Edition

GuardinginclusionsTypically,aC++programwillhavemany.hheaderfilesandasingle.cppimplementationfilecontainingthemainprogram.Headerfilesmayoftencontainoneormore#includedirectivestomakeotherclassesorfunctionsavailablefromotherheaderfiles,andcancauseduplicationwheredefinitionsappearintwofiles.Forexample,whereaheaderfileincludesanotherheaderfilecontainingafunctiondefinition,thecompilerwillconsiderthatdefinitiontoappearineachfile–socompilationwillfail.

Thepopularsolutiontothisproblemofre-definitionemployspreprocessordirectivestoensurethecompilerwillonlybeexposedtoasingledefinition.Theseareknownas“inclusionguards”andcreateauniquemacronameforeachheaderfile.Traditionally,thenameisanuppercaseversionofthefilename,withthedotchangedtoanunderscore.Forexample,RUM_Hforafilerum.h.

Inclusionguardsarealsoknownas“macroguards”orsimplyas“includeguards”.

Increatingamacrotoguardagainstduplication,an#ifndefdirectivefirstteststoseeifthedefinitionhasalreadybeenmadebyanotherheaderfileincludedinthesameprogram.Ifthedefinitionalreadyexists,thecompilerignorestheduplicatedefinition,otherwisea#definedirectivewillpermitthecompilertousethedefinitioninthatheaderfile:

add.h

triple.h

guard.cpp

Page 303: C++ Programming in easy steps, 5th Edition

Createaheaderfilenamed“add.h”containingtheinlinedeclarationofan“add”functioninlineint add(int x,int y){return(x+y);}

Now,createaheaderfilenamed“triple.h”containingaprocessordirectivetomaketheaddfunctionavailableforuseintheinlinedeclarationofa“triple”function#include“add.h”

inlineint t riple(x){returnadd(x,add(x,x));}

Startanewprogramwithpreprocessordirectivestomakeboththeaddandtriplefunctionsavailable#include“add.h”#include“t riple.h”

Specifythelibraryclassestoincludeandthenamespace#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingstatementsthatcallboththeadd()andt riple()functionsfromtheincludedheadersint main(){

cout <<“9+3=“<<add(9,3)<<endl;cout <<“9x3=“<<t riple(9)<<endl;return0;

}

Savethefiles,thenattempttocompiletheprogramtoseecompilationfailbecausetheaddfunctionappearstobedefinedtwice–in“add.h”andbyinclusionin“triple.h”

Edittheheaderfile“add.h”toenclosetheinlinefunctiondeclarationwithinapreprocessorinclusionguard#ifndefADD_H#defineADD_H

inlineint add(int x,int y){return(x+y);}

#endif

Savethemodifiedfile,thencompileandruntheprogram–compilationnowsucceedsbecausetheinclusionguardpreventstheapparentre-definitionoftheaddfunction

Page 304: C++ Programming in easy steps, 5th Edition

Usetheconventionalnamingscheme,wherethemacronameresemblesthefilename,toavoidconflicts.

Allheaderfilesshouldcontainheaderguards–addaTRIPLE_Hmacrotothet riple.hfile.

Page 305: C++ Programming in easy steps, 5th Edition
Page 306: C++ Programming in easy steps, 5th Edition

UsingmacrofunctionsThe#definedirectivecanbeusedtocreatemacrofunctionsthatwillbesubstitutedinthesourcecodebeforecompilation.

Apreprocessorfunctiondeclarationcomprisesamacroname,immediatelyfollowedbyparenthesescontainingthefunction’sarguments–itisimportantnottoleaveanyspacebetweenthenameandtheparentheses.Thedeclarationisthenfollowedbythefunctiondefinitionwithinanothersetofparentheses.Forexample,apreprocessormacrofunctiontohalfanargumentlookslikethis:

#defineHALF(n)(n/2)

Careshouldbetakenwhenusingmacrofunctions,becauseunlikeregularC++functions,theydonotperformanykindoftypechecking–soit’squiteeasytocreateamacrothatcauseserrors.Forthisreason,inlinefunctionsareusuallypreferabletomacrofunctions,butbecausemacrosdirectlysubstitutetheircode,theyavoidtheoverheadofafunctioncall–sotheprogramrunsfaster.Theresultingdifferencecanbeseeninthefirsttemporaryfilecreatedduringthecompilationprocess:

macro.cpp

Startanewprogrambydefiningtwomacrofunctionstomanipulateasingleargument#defineSQUARE(n)(n*n)#defineCUBE(n)(n*n*n)

Afterthemacrofunctiondefinitions,specifythelibraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Next,declaretwoinlinefunctionstomanipulateasingleargument–justlikethemacrofunctionsdefinedaboveinlineint square(int n){return(n*n);}inlineint cube(int n){return(n*n*n);}

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Atthestartofthemainfunctionblock,declareandinitializeanintegervariable

Page 307: C++ Programming in easy steps, 5th Edition

int num=5;

Now,insertstatementstocalleachmacrofunctionandeachcomparableinlinefunctioncout <<“MacroSQUARE:”<<SQUARE(num)<<endl;cout <<“Inlinesquare:”<<square(num)<<endl;cout <<“MacroCUBE:”<<CUBE(num)<<endl;cout <<“Inlinecube:”<<cube(num)<<endl;

Savethefile,thencompiletheprogram,savingthetemporaryfilesandruntheprogramc++macro.cpp-save-temps-omacro.exe

Openthetemporary“.ii”fileinaplaintexteditor,likeNotepad,toseethatthemacrofunctionshavebeendirectlysubstitutedineachoutputstatement

Usinguppercaseformacronamesensuresthatmacrofunctionswillnotconflictwithregularlowercasefunctionnames.

Page 308: C++ Programming in easy steps, 5th Edition

Aninlinefunctionsavestheoverheadofcheckingbetweenafunctionprototypedeclarationanditsdefinition.

Page 309: C++ Programming in easy steps, 5th Edition
Page 310: C++ Programming in easy steps, 5th Edition

BuildingstringsThepreprocessor# operatorisknownasthe“stringizing”operator,asitconvertsaseriesofcharacterspassedasamacroargumentintoastring–addingdoublequotestoenclosethestring.

Allwhitespacebeforeoraftertheseriesofcharacterspassedasamacroargumenttothestringizingoperatorisignored,andmultiplespacesbetweencharactersisreducedtojustonespace.

Thestringizingoperatorisusefultopassstringvaluestoapreprocessor#definedirectivewithoutneedingtosurroundeachstringwithdoublequotes.

Amacrodefinitioncancombinetwotermsintoasingletermusingthe## mergingoperator.Wherethecombinedtermisavariablename,itsvalueisnotexpandedbythemacro–itsimplyallowsthevariablenametobesubstitutedbythemacro.

strung.cpp

Startanewprogrambydefiningamacrotocreateastringfromaseriesofcharacterspassedasitsargument,tosubstituteinanoutputstatement#defineLINEOUT(st r)cout <<#st r<<endl

Defineasecondmacrotocombinetwotermspassedasitsargumentsintoavariablename,tosubstituteinanoutputstatement#defineGLUEOUT(a,b)cout <<a##b<<endl

Afterthemacrodefinitions,specifythelibraryclassestoinclude,andanamespaceprefixtouse#include<st ring>#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Atthestartofthemainfunctionblock,declareandinitializeastringvariable,thenappendafurtherstringst ringlongerline=“Theycarriedanet ”;longerline+=“andtheirheartswereset”;

Page 311: C++ Programming in easy steps, 5th Edition

Now,addstatementstooutputtextusingthemacrosLINEOUT(Inabowltoseawent wisementhree);LINEOUT(Onabrilliant night inJune);GLUEOUT(longer,line);LINEOUT(Onfishingupthemoon.);

Savethefile,thencompiletheprogram,savingthetemporaryfilesandruntheprogramc++st rung.cpp-save-temps-ost rung.exe

Openthetemporary“.ii”fileinaplaintexteditor,likeNotepad,toseethatthestringvaluesandthevariablenamehavebeensubstitutedintheoutputstatements

Noticethatthesecondstatementcontainsmultiplespaces,whichwillberemovedbythestringizingoperator.

Themergingoperatorisalternativelyknownasthe“token-pasting”operator,asitpastestwo“tokens”together.

Page 312: C++ Programming in easy steps, 5th Edition
Page 313: C++ Programming in easy steps, 5th Edition

DebuggingassertionsItissometimeshelpfultousepreprocessordirectivestoassistwithdebuggingprogramcode–bydefininganASSERT macrofunctiontoevaluateaspecifiedconditionforaBooleanvalue.

TheconditiontobeevaluatedwillbepassedfromthecallerastheASSERT functionargument.Thefunctioncanthenexecuteappropriatestatementsaccordingtotheresultoftheevaluation.Multiplestatementscanbeincludedinthemacrofunctiondefinitionbyaddingabackslash\attheendofeachline,allowingthedefinitiontocontinueonthenextline.

Youcancomment-outsectionsofcodewhendebuggingusingC-style/**/commentoperators.

NumerousstatementscallingtheASSERT functioncanbeaddedtotheprogramcodetomonitoraconditionastheprogramproceeds.Forexample,tocheckthevalueofavariableasitchanges.

Usefully,anASSERT functioncanbecontrolledbyaDEBUGmacro.ThisallowsdebuggingtobeeasilyturnedonandoffsimplybychangingthevalueoftheDEBUGcontrolmacro:

assert.cpp

StartanewprogrambydefiningaDEBUGmacrowithan“on”valueofone–tocontrolanASSERTfunction#defineDEBUG1

Next,addamacroif-elifstatementblocktodefinetheASSERTfunctionaccordingtothecontrolvalue#if(DEBUG==1)

//Definit ionfor“on”goeshere.#elif(DEBUG==0)

//Definit ionfor“off”goeshere.#endif

InthetoppartoftheASSERTfunctionstatementblockinsertadefinitionforwhenthedebuggingcontrolissetto“on”–tooutputfailuredetailsfrompredefinedmacros#defineASSERT(expr) \

Page 314: C++ Programming in easy steps, 5th Edition

cout <<#expr<<“...”<<num; \if(expr!=t rue) \{ \cout <<“Failsinfile:”<<__FILE__; \cout <<“at line:”<<__LINE__<<endl; \

} \elsecout <<“Succeeds”<<endl;

Donotplaceabackslashcontinuationcharacteronthelastlineofthedefinition,andremembertousethe#stringizingoperatortooutputtheexpressionasastring.

InthebottompartoftheASSERTfunctionstatementblock,insertadefinitionforwhenthedebuggingcontrolissetto“off”–tosimplyoutputthecurrentvariablevalue#defineASSERT(result )\cout <<“Numberis“<<num<<endl;

Afterthemacrodefinitions,specifythelibraryclassestoinclude,andanamespaceprefixtouse#include<iost ream>usingnamespacestd;

Addamainfunctioncontainingafinalreturnstatementint main(){

//Programcodegoeshere.return0;

}

Atthestartofthemainfunctionblock,declareandinitializeanintegervariable,thencallthemacroASSERTfunctiontocheckitsvalueasitgetsincrementedint num=9;ASSERT(num<10);num++; ASSERT(num<10);

Save,compile,andruntheprogramtoseetheoutput

Edittheprogramtoturndebuggingoffbychangingthecontrolvalue,thenrecompileandre-runtheprogram#defineDEBUG0

Page 315: C++ Programming in easy steps, 5th Edition

Predefinedmacronamesareprefixedbyadouble-underscoreandsuffixedbyadouble-underscore.

Additionally,thecurrentdateandtimecanbeoutputfromthe__DATE__and__TIME__predefinedmacros.

Page 316: C++ Programming in easy steps, 5th Edition
Page 317: C++ Programming in easy steps, 5th Edition

Summary• TheC++compiler ’s-save-tempsoptionsavesthetemporaryfilescreatedduringthe

compilationprocessforexamination.

• Compilationfirstwritesprogramcodeandincludedlibrarycodeintoasingle.iitextfile,whichisthentranslatedintolow-levelAssemblylanguageasa.stextfile.

• Assemblylanguage.sfilesaretranslatedtomachinecodeas.oobjectfiles,whichareusedtocreatetheexecutableprogram.

• A#definedirectivedefinesamacronameandavaluethatthepreprocessorshouldsubstituteforthatnameinprogramcode.

• Thepreprocessorcanbemadetoperformconditionaltestsusing#ifdef,#ifndef,and#endifdirectives.

• Preprocessoralternativescanbeprovidedusing#if,#else,and#elifdirectives,andadefinitioncanberemovedusing#undef.

• Eachheaderfileshoulduseinclusionguardstopreventaccidentalmultipledefinitionofthesameclassorfunction.

• Themacronameofaninclusionguardisanuppercaseversionofthefilename,butwiththedotreplacedbyanunderscore.

• A#definedirectivemayalsodefineamacrofunctionthatwillbesubstitutedinprogramcodeinplaceofthemacroname.

• Inlinefunctionsareusuallypreferabletomacrofunctionsbecause,unlikemacrofunctions,theyperformtype-checking.

• Thepreprocessor# stringizingoperatorconvertsaseriesofcharacterspassedasamacroargumentintoastringvalue.

• Twotermscanbecombinedintoasingletermbythepreprocessor## mergingoperator.

• AnASSERT macrofunctionisusefulfordebuggingcode,andmaybecontrolledbyaDEBUGmacrotoeasilyturndebuggingonoroff.

Page 318: C++ Programming in easy steps, 5th Edition

10

Programmingvisually

ThischapterbringstogetherelementsfrompreviouschapterstobuildacompleteC++applicationinavisual

programmingenvironment.

StartingaUniversalprojectInsertingpagecomponentsImportingprogramassetsDesigningthelayoutAddingruntimefunctionTestingtheprogramAdjustingtheinterfaceDeployingtheapplicationSummary

Page 319: C++ Programming in easy steps, 5th Edition
Page 320: C++ Programming in easy steps, 5th Edition

StartingaUniversalprojectWindows10introducedtheUniversalWindowsPlatform(UWP)thatenablesyoutocreateasingleapplicationthatwillrunonanymodernWindows-baseddevice–phone,tablet,orPC.

TheinterfacelayoutofaUWPapplicationusestheeXtensibleApplicationMarkupLanguage(XAML)tospecifycomponents.

TheexampleinthischapterisforVisualStudio2015onWindows10–itwon’tworkwithearlierversions.

InordertodevelopappsfortheUWP,youshouldberunningthelatestversionofWindows10,andyourVisualStudioIDEmustincludetheUniversalWindowsAppDevelopmentTools:

Universal

OpenControlPanel,ProgramsandFeatures,thenright-clickontheVisualStudioitemandselectChange–tolaunchtheVisualStudioinstaller

SelectalloptionsintheUniversalWindowsAppDevelopmentToolscategory,thenclicktheNextbutton–todownloadandinstallthetools

Page 321: C++ Programming in easy steps, 5th Edition

Afterinstallationofthetools,opentheVisualStudioIDE

AUWPapplicationisalsoknownasa“UWA”–UniversalWindowsApplication.

DependinguponyourchoiceswhenyouinstalledVisualStudio,youmayseetheoptionscheckedwhentheinstallerlaunches,toindicateyoualreadyhavetheUniversalWindowsAppDevelopmentTools.

Next,selectFile,New,ProjectandcreateanewBlankApp(UniversalWindows)projectcalled“Universal”

Page 322: C++ Programming in easy steps, 5th Edition

Whenaskedtoselectthetargetandminimalplatformversions,simplyclickOKtoacceptthedefaultoptions

AfterVisualStudiocreatesthenewproject,selectView,SolutionExplorertoexaminethegeneratedfiles:

• AsetoflogoimagesinanAssetsfolder

• InternalXAMLandC++Appfiles

• XAMLandC++filesfortheMainPage–hereiswhereyouwillcreateinterfacecomponentsandfunctionalcode

• OthermiscellaneousPackagefiles

InWindows10,youshouldensurethattheDeveloperModeoptionisenabledinSettings,Update&Security,Fordevelopers.

ThesefilesareessentialtoallUWPappsusingC++,andexistineveryprojectVisualStudiocreatestotargettheUniversalWindowsPlatformwithC++.

Page 323: C++ Programming in easy steps, 5th Edition
Page 324: C++ Programming in easy steps, 5th Edition

InsertingpagecomponentsVisualStudioprovidesatwo-partwindowtoinsertinterfacecomponentsintoaUWPapp.ThiscomprisesaDesignviewofthecomponentsandaXAMLviewfortheXAMLcode:

Universal

OpenSolutionExplorerthendouble-clickonMainPage.xaml–tolaunchthetwo-partwindow

Seethatbydefault,theDesignviewdisplaysablankcanvasinPortraitmode

Page 325: C++ Programming in easy steps, 5th Edition

Explorethesebuttonstochangethemagnificationandgridcharacteristics.

ClicktheadjacentbuttoninDesignviewtochangetheblankcanvastoLandscapemode

XAMLispronounced“zammel”.

ThereisaToolboxthatletsyouaddcomponentsontothecanvas,butyouwillneedtoeditthemintheXAMLcodelater.Inthisexample,thecomponentsarecreatedinXAMLcodefromtheverystart.

Now,seethatbydefault,theXAMLviewrevealsthereare<Grid></Grid>tags–thisistherootelementofthecanvasinwhichyoucanaddcomponentelements

Componentelementsarebestnestedwithina<StackPanel>element,asthiscanbegivenanx:NameforreferenceinfunctionalcodeandanOrientat ionattributetospecifythedirectioninwhichthenestedelementsshouldappear.Commoncomponentelementsinclude<Image>,<TextBox>,<TextBlock>(label),and<But ton>.Several<StackPanel>elementscanbenestedwithineachothertodeterminetheHorizontalandVert icallayoutofcomponents:

Insertelementsbetweentheroot<Grid></Grid>tagssotheXAMLviewcodelookspreciselylikethis:

Page 326: C++ Programming in easy steps, 5th Edition

AsyouaddthecomponentelementsinXAMLview,theyappearintheDesignviewuntilitlookslikethis:

Thex:prefixbeforetheNameattributereferstotheXAMLschemausedbyUWPapps.

Theouter<StackPanel>isahorizontallayoutcontainingan<Image>andanested<Stackpanel>.Thenested<StackPanel>isaverticallayoutcontainingtwofurther<StackPanel>elementsthateachdisplaytheircomponentshorizontally.

Page 327: C++ Programming in easy steps, 5th Edition

Noticethateach<TextBlock>elementhasaText attributethatcanbereferencedinfunctionalcode.E.g.t extBlock1->Text .

Page 328: C++ Programming in easy steps, 5th Edition
Page 329: C++ Programming in easy steps, 5th Edition

ImportingprogramassetsInordertohaveaXAML<Image>componentdisplayagraphic,animagefilefirstneedstobeaddedtotheproject’sAssetsfolder.ItcanthenbeassignedtoaSourceattributeofthe<Image>tag:

Universal

OpenSolutionExplorer,thenright-clickontheAssetsfolderandchooseAddfromthecontextmenu

Now,chooseExistingItemfromthenextcontextmenu–toopenanAddExistingItemdialogbox

IntheAddExistingItemdialog,browsetothelocationofanimagethenselectthefileandclicktheAddbutton

Page 330: C++ Programming in easy steps, 5th Edition

Animagefordisplaymaybeinanypopularfileformat–suchas.bmp,.gif,.jpg,.png,or.t if.

InSolutionExplorer,theselectedimagefilenowappearsintheproject’sAssetfolder

SelecttheImagecomponentinDesignerview,thenclickView,Propertiestorevealitsproperties

InthePropertieswindow,expandtheCommoncategory,thenclicktheSourceitem’sarrowbuttonandselecttheaddedimagefromthedrop-downlist

TheimagenowappearsintheDesignview,anditspathgetsaddedtotheXAMLviewcodeandSourceproperty

Page 331: C++ Programming in easy steps, 5th Edition

ExploretheAppearanceandTransformoptionsinanimage’sPropertieswindowtodiscoverhowyoucanmodifyhowitwillbedisplayed.

Page 332: C++ Programming in easy steps, 5th Edition
Page 333: C++ Programming in easy steps, 5th Edition

DesigningthelayoutTocompletetheapp’slayout,designattributescanbeaddedtotheXAMLelementtagstospecifywhattheywilldisplayandpreciselywhereintheinterfacetheywillappear:

Universal

OpenMainPage.xaml,thenaddtwoattributestotheouter<StackPanel>elementtofixitspositionHorizontalAlignment =”Left ”Vert icalAlignment =”Top”

Next,editthe<Image>elementbymodifyingtheinitialassignedvalueof200–toincreaseitswidthWidth=”300”

Now,addanattributetothenested<StackPanel>elementtofixitspositionVert icalAlignment =”Center”

Then,editallsix<TextBlock>elementsalike,tospecifytheirinitialcontent,width,andmarginonallfoursidesText =”...”Width=”20”Margin=”15”Text =”...”Width=”20”Margin=”15”Text =”...”Width=”20”Margin=”15”Text =”...”Width=”20”Margin=”15”Text =”...”Width=”20”Margin=”15”Text =”...”Width=”20”Margin=”15”

Editthefirst<But ton>elementtorenameit,specifyitsbuttonlabelcontentandmarginonallfoursidesx:Name=“BtnPick”Content =“Get MyLuckyNumbers”Margin=“15”

Editthesecond<But ton>elementtorenameitandspecifyitsbuttonlabelcontentx:Name=“BtnReset”Content =“Reset”

Finally,addanattributetoeachrespective<But ton>elementtospecifytheirinitialstateIsEnabled=“True”IsEnabled=“False”

AsingleMarginvaluesetsallfourmarginsaroundthatcomponent.Youcanspecify

Page 334: C++ Programming in easy steps, 5th Edition

twovaluestosetleft&right,top&bottommargins,e.g.Margin=“10,30”.Alternatively,youcanspecifyfourvaluestosetleft,top,right,bottommarginsindividually,e.g.Margin=“10,30,10,50”.

Theorderinwhichtheattributesappearineachelementisunimportant,buttheelementswithintheMainPage.xamlfileshouldnowlooksimilartothescreenshotbelow:

YoucanoptionallyaddMargin=“0”attributestoexplicitlyrequireelementstohavenomarginwidth.

AsyoumakechangestotheXAMLviewcode,thecomponentlayoutgetschangedaccordinglyintheDesignviewandshouldnowlooklikethis:

TheDesignviewshowsthecomponents’initialstate–theResetbuttonappears

Page 335: C++ Programming in easy steps, 5th Edition

grayedout,asitisnotenabled.

Page 336: C++ Programming in easy steps, 5th Edition
Page 337: C++ Programming in easy steps, 5th Edition

AddingruntimefunctionHavingcompletedtheapplicationcomponentlayoutwithXAMLelementsabove,youarenowreadytoaddfunctionalitywithC++programmingcode:

Universal

InDesignview,double-clickontheBtnPickbutton

TheMainPage.xaml.cppcode-behindpageopensintheCodeEditoratageneratedBtnPick_Clickevent-handler

IntheBtnPick_Clickevent-handlerblock,insertthesestatementstocreatearandomizedarrayofintegersbetween1and59int i,j,k,seq[60];srand((int )t ime(0));

for(i=1;i<60;i++)seq[i]=i;for(i=1;i<60;i++)

{j=((int )rand()%59)+1;k=seq[i];seq[i]=seq[j];seq[j]=k;

}//Statementstobeinsertedhere(Steps4-5).

Next,insertstatementstoassignsixarrayelementvaluestothe<TextBlock>componentst extBlock1->Text =seq[1].ToSt ring();t extBlock2->Text =seq[2].ToSt ring();t extBlock3->Text =seq[3].ToSt ring();t extBlock4->Text =seq[4].ToSt ring();t extBlock5->Text =seq[5].ToSt ring();t extBlock6->Text =seq[6].ToSt ring();

Next,insertstatementstosetthe<But ton>statesBtnPick->IsEnabled=false;BtnReset ->IsEnabled=t rue;

ReturntoMainPage.xaml,theninDesignview,double-clickontheBtnReset button

TheMainPage.xaml.cppcode-behindpageopensintheCodeEditoratageneratedBtnReset_Clickevent-handler

Page 338: C++ Programming in easy steps, 5th Edition

Thesrand()functionseedsarandomnumbergeneratorwiththecurrentsystemtime,sosubsequentcallstotherand()functionreturndifferentpseudorandomnumbers.

ThereisnoLabelcomponentinUWPapps;itiscalledaTextBlockinstead.

ThereisnoEnabledpropertyinUWPapps;buttonitiscalledIsEnabledinstead.

IntheBtnReset_Clickevent-handlerblock,insertstatementstoassignstringstothe<TextBlock>componentst extBlock1->Text =“...”;t extBlock2->Text =“...”;t extBlock3->Text =“...”;t extBlock4->Text =“...”;t extBlock5->Text =“...”;t extBlock6->Text =“...”;//Statementstobeinsertedhere(Step9).

Finally,insertstatementstosetthe<But ton>statesBtnPick->IsEnabled=t rue;BtnReset ->IsEnabled=false;

TheBtnReset buttonsimplyreturnsthe<TextBox>and<But ton>componentstotheiroriginalstates.

TheMainPage.xaml.cppcode-behindpageshouldnowlooklikethescreenshotbelow:

Page 339: C++ Programming in easy steps, 5th Edition

ReturntotheMainPage.xamlfile,theninXAMLview,seethatattributeshavebeenautomaticallyaddedtothe<But ton>elementstocalltheevent-handlercode

Noticethatthefirstforloopcontainsonlyonestatementtobeexecutedoneachiteration,sobracesarenotrequired.

Page 340: C++ Programming in easy steps, 5th Edition
Page 341: C++ Programming in easy steps, 5th Edition

TestingtheprogramHavingaddedfunctionalitywithC++codeabove,youarenowreadytotesttheprogramfortwodevices:

Universal

OntheVisualStudiostandardtoolbar,selectDebugforx64architectureandLocalMachineoptions,thenclicktheStartbuttontoruntheappforaPCdevice

Waitwhiletheapplicationgetsbuiltandloaded,thenclickthebuttonstotryouttheirfunctionality

Page 342: C++ Programming in easy steps, 5th Edition

YoumusthaveyourPCsettoDeveloperModeinSettings,Update&Security,Fordevelopers.

TheapplooksgoodonPCdevices–numbersarebeingrandomizedandthebuttonstatesarechangingasrequired.

Now,ontheVisualStudiostandardtoolbar,selectDebug,StopDebuggingtoexittherunningprogram

YoucansafelyignoretheDEBUGnumbersthatappearintheblackboxes,butifyouprefernottoseethem,selectProject,ProjectNameProperties,BuildthenunchecktheDefineDEBUGconstantoption.

OntheVisualStudiostandardtoolbar,selectDebugforx86architectureandsmallMobileEmulatoroptions,thenclicktheStartbuttontoruntheappforamobiledevice

Page 343: C++ Programming in easy steps, 5th Edition

Waitwhiletheemulatorstartsup–thistakesawhile

Whentheapplicationgetsbuiltandloaded,youseethecontrolsarenotvisible–soyoucan’ttryouttheirfunctionality!

What’sgoingonhere?Clickoneoftheemulator ’sRotatebuttonstoflipitovertoLandscapeorientationandlookforclues

Ah-ha!Someofthecontrolsarenowvisible,butthisisunsatisfactory–adjustmentswillbeneededtotheinterfacelayoutsotheapplooksgoodonmobiledevices

Again,ontheVisualStudiostandardtoolbar,selectDebug,StopDebuggingtoexittherunningprogram

Testontheemulatorwithlowestmemoryandsmallestscreenanditshouldbefinerunningonthoseemulatorswithbetterfeatures.

Page 344: C++ Programming in easy steps, 5th Edition

DonotclicktheXbuttonontheemulatorwindowtostoptherunningprogram,asthatwillalsoclosetheemulator.

Page 345: C++ Programming in easy steps, 5th Edition
Page 346: C++ Programming in easy steps, 5th Edition

AdjustingtheinterfaceTheapptestformobiledevicesabovefailedtosatisfactorilypresentthecontrols,astheinterfaceistoowideforsmallscreendevices.Happily,theinterfacecanbemadetoadapttodifferentscreensizessoitcanalsolookgoodonmobiledevices.Theadaptationreliesuponrecognizingthescreensizeandchangingtheorientationofa<StackPanel>elementinXAMLfornarrowscreendevices:

Universal

OpenMainPage.xaml,theninXAMLviewaddtheseelementsimmediatelybelowtheopening<Grid>elementandbeforethecomponentelements<VisualStateManager.VisualStateGroups>

<VisualStateGroup>

<!--Elementstobeinsertedhere(Steps2-3)-->

</VisualStateGroup></VisualStateManager.VisualStateGroups>

Next,insertelementstorecognizewidescreens<VisualStatex:Name=“wideState”>

<VisualState.StateTriggers><Adapt iveTriggerMinWindowWidth=“641”/>

</VisualState.StateTriggers>

</VisualState>

Now,insertelementstorecognizenarrowscreensandtochangetheOrientat ionoftheouter<StackPanel>

<VisualStatex:Name=“narrowState”>

<VisualState.StateTriggers><Adapt iveTriggerMinWindowWidth=“0”/>

</VisualState.StateTriggers>

<VisualState.Set ters><Set terTarget =“MainStack.Orientat ion”Value=“Vert ical”/>

</VisualState.Set ters>

</VisualState>

ThebeginningoftheMainPage.xamlfileshouldnowlooksimilartothescreenshotbelow:

Page 347: C++ Programming in easy steps, 5th Edition

XAMLcoderecognizesthesame<!---->commenttagsthatareusedinHTMLcode.

Rememberthattheouter<StackPanel>inthisappcontainsan<Image>andanested<StackPanel>displayedhorizontally,side-by-side.Ifdisplayedvertically,theyshouldappearoneabovetheother.

Selectx64andLocalMachinetoruntheappforaPCdeviceoncemore–itstilllooksandfunctionswell

Nowselectx86andMobileEmulatortoruntheappforamobiledevice–italsonowlooksandfunctionswell

Page 348: C++ Programming in easy steps, 5th Edition

YoucanhaveVisualStudionicelyformattheXAMLcodebypressingCtrl+K,Ctrl+D.

Althoughanappmayworkwellonanemulator,itisrecommendedyoualwaystestonactualdevicesbeforedeployment.

Page 349: C++ Programming in easy steps, 5th Edition
Page 350: C++ Programming in easy steps, 5th Edition

DeployingtheapplicationHavingtestedtheappinaMobileEmulatorabove,itcannowbetestedonarealdevicebeforedeployment:

Universal

OnaWindows10deviceselectDevelopermodefromtheSettings,Update&Security,Fordevelopersmenu

Next,connectthedevicetoyourPCviaaUSBsocket

OntheVisualStudiotoolbar,selectDebugforARMarchitectureandDeviceoptions,thenclicktheStartbuttontoruntheappontheconnecteddevice

Waitwhiletheapplicationgetsbuiltandloaded,thentapthebuttonstotryouttheirfunctionality

Page 351: C++ Programming in easy steps, 5th Edition

YoucanchoosetheRemoteMachineoptiontotestviaanetworkconnection.

Theapplooksgood,numbersarebeingrandomized,andthebuttonstatesarechangingasrequired–theappcanbedeployed.

RemovetheDebugversionoftheappfromthedevice

InSolutionExplorer,addlogoimagestotheAssetsfolder,thendouble-clickonPackage.appmanifestandaddthemtoVisualAssets

AddthreelogoimagestotheAssetsfolderoftherequiredsizes,thenclickthese

Page 352: C++ Programming in easy steps, 5th Edition

buttonstoselectthemtobetheapptiles.Youcanalsoaddtileimages,aSplashScreenimage,orselecttheApplicationtabandchangetheapp’sDisplayname–forexamplemaybeto“LuckyNumbers”.

OntheVisualStudiotoolbar,selectReleaseforARMarchitectureandDeviceoptions,thenclickBuild,DeploySolutiontobuildandinstalltheReleaseversion

YoucanuseyourC++programmingskillstobuildappsforAndroidandiOSwiththeVisualStudio2015add-in,“VisualC++forCross-PlatformMobileDevelopment”.Discovermoreatmsdn.microsoft .com/en-us/library/dn707591.aspx

Page 353: C++ Programming in easy steps, 5th Edition
Page 354: C++ Programming in easy steps, 5th Edition

Summary• TheUniversalWindowsPlatform(UWP)enablesasingleapptorunonanymodern

Windows-baseddevice.

• TheeXtensibleApplicationMarkupLanguage(XAML)isusedtospecifycomponentsandlayoutonUWPapps.

• TheUniversalWindowsAppDevelopmentToolsareneededinordertodevelopUWPapps.

• TheBlankApp(UniversalWindows)templatecanbeusedtocreateanewUWPproject.

• VisualStudioprovidesagraphicalDesignviewandatextcodeXAMLviewfortheMainPage.xamlfile.

• ComponentelementscanbeplacedwithinXAML<StackPanel>elementstoarrangetheirorientation.

• ImagefilescanbeaddedtotheAssetsfolderandassignedtoXAML<Image>elementsfordisplayontheinterface.

• SpacecanbeaddedaroundacomponentbyaddingaMarginattributeandassignedvaluewithinitselementtag.

• FunctionalC++programmingcodecanbeaddedtotheMainPage.xaml.cppcode-behindpage.

• TheDeveloperModesettingmustbeenabledintheWindows10optionsinordertodevelopandtestUWPapps.

• AUWPappcanbetestedinDebugmodeontheLocalMachine,aMobileEmulator,andaconnectedDevice.

• TheinterfaceofaUWPappcanadapttodifferentscreensizesbychangingtheorientationof<StackPanel>elements.

• ImagefilescanbeaddedtotheAssetsfolderforassignmentaslogosinthePackage.appmanifestwindow.

• TheReleaseversioncanbedeployedbyselectingthetargetconfiguration,thenusingtheBuild,DeploySolutionmenu.

Page 355: C++ Programming in easy steps, 5th Edition
Page 356: C++ Programming in easy steps, 5th Edition
Page 357: C++ Programming in easy steps, 5th Edition