c++ programming in easy steps, 5th edition
TRANSCRIPT
MikeMcGrath
C++Programming
FifthEdition
IneasystepsisanimprintofInEasyStepsLimited16HamiltonTerrace.HollyWalk.LeamingtonSpaWarwickshire.CV324LYwww.ineasysteps.com
FifthEdition
Copyright© 2017byInEasyStepsLimited.Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutpriorwrittenpermissionfromthepublisher.
NoticeofLiabilityEveryefforthasbeenmadetoensurethatthisbookcontainsaccurateandcurrentinformation.However,InEasyStepsLimitedandtheauthorshallnotbeliableforanylossordamagesufferedbyreadersasaresultofanyinformationcontainedherein.
TrademarksAlltrademarksareacknowledgedasbelongingtotheirrespectivecompanies.
Contents
1GettingstartedIntroducingC++InstallingacompilerWritingyourfirstprogramCompiling&runningprogramsCreatingvariablesEmployingvariablearraysEmployingvectorarraysDeclaringconstantsSummary
2PerformingoperationsDoingarithmeticAssigningvaluesComparingvaluesAssessinglogicExaminingconditionsEstablishingsizeSettingprecedenceCastingdatatypesSummary
3MakingstatementsBranchingwithifSwitchingbranchesLoopingforLoopingwhileDeclaringfunctionsPassingargumentsOverloadingfunctionsOptimizingfunctionsSummary
4HandlingstringsCreatingstringvariablesGettingstringinputSolvingthestringproblemDiscoveringstringfeaturesJoining&comparingstringsCopying&swappingstringsFindingsubstringsReplacingsubstringsSummary
5ReadingandwritingfilesWritingafileAppendingtoafileReadingcharacters&linesFormattingwithgetlineManipulatinginput&outputPredictingproblemsRecognizingexceptionsHandlingerrorsSummary
6PointingtodataUnderstandingdatastorageGettingvalueswithpointersDoingpointerarithmeticPassingpointerstofunctionsMakingarraysofpointersReferencingdataPassingreferencestofunctionsComparingpointers&referencesSummary
7CreatingclassesandobjectsEncapsulatingdataCreatinganobjectCreatingmultipleobjectsInitializingclassmembersOverloadingmethodsInheritingclasspropertiesCallingbaseconstructorsOverridingbasemethodsSummary
8HarnessingpolymorphismPointingtoclassesCallingavirtualmethodDirectingmethodcallsProvidingcapabilityclassesMakingabstractdatatypesBuildingcomplexhierarchiesIsolatingclassstructuresEmployingisolatedclassesSummary
9ProcessingmacrosExploringcompilationDefiningsubstitutesDefiningconditionsProvidingalternativesGuardinginclusions
UsingmacrofunctionsBuildingstringsDebuggingassertionsSummary
10ProgrammingvisuallyStartingaUniversalprojectInsertingpagecomponentsImportingprogramassetsDesigningthelayoutAddingruntimefunctionTestingtheprogramAdjustingtheinterfaceDeployingtheapplicationSummary
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
entitledAllCodeExamplestodownloadthearchive
Now,extractthearchivecontentstoanyconvenientlocationonyourcomputer
Isincerelyhopeyouenjoydiscoveringthepowerful,expressivepossibilitiesofC++ProgrammingandhaveasmuchfunwithitasIdidinwritingthisbook.
1
Gettingstarted
WelcometotheexcitingworldofC++programming.ThischapterdemonstrateshowtocreateasimpleC++programand
howtostoredatawithinaprogram.
IntroducingC++InstallingacompilerWritingyourfirstprogramCompiling&runningprogramsCreatingvariablesEmployingvariablearraysEmployingvectorarraysDeclaringconstantsSummary
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.
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.
“ISO”isnotanacronymbutisderivedfromtheGreekword“isos”meaning“equal”–asin“isometric”.
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.
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:
LocationaddressesinthePathstatementmustendwitha;semi-colon.
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:
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
executedsuccessfully.
TheC++compileralsosupportsmultiple-lineC-stylecommentsbetween/*and*/–buttheseshouldonlyeverbeusedinC++programmingto“comment-out”sectionsofcodewhendebugging.
Noticehowtheprogramcodeisformattedusingspacingandindentation(collectivelyknownaswhitespace)toimprovereadability.AllwhitespaceisignoredbytheC++compiler.
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
TorunthegeneratedexecutableprogramfileinWindows,simplyenterthefilenameatthepromptinthe“MyPrograms”directory–optionally,thefileextensionmaybeomitted.InLinux,thefullfilenamemustbeused,precededbya./dot-slash–asLinuxdoesnotlookinthecurrentdirectoryunlessitisexplicitlydirectedtodoso:
AllcommandlineexamplesinthisbookhavebeencompiledandtestedwiththelatestGNUC++Compileravailableatthetimeofwriting–theymaynotreplicateexactlywithothercompilers.
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
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;
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”.
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’};
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;
cout <<“coords[1][2]:”<<coords[1][2]<<endl;
Save,compile,andruntheprogramtoseetheoutput
Wherepossible,variablenamesshouldnotbeabbreviations–abbreviatednamesareonlyusedinthisbook’sexamplesduetospacelimitations.
Theloopstructures,introducedinChapterThree,areoftenusedtoiteratearrayelements.
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].
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
Theexamplehereshowshowtousealooptopopulateavectorwithdifferentinitialvaluesineachelement.
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.
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
InthePIdeclaration,the*characteristheC++multiplicationoperator,andthebackslashcharacterin\”escapesthequotemarkfromrecognition–sothestringdoesnotgetterminatedprematurely.
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.
2
Performingoperations
ThischapterintroducestheC++operatorsanddemonstratestheoperationstheycanperform.
DoingarithmeticAssigningvaluesComparingvaluesAssessinglogicExaminingconditionsEstablishingsizeSettingprecedenceCastingdatatypesSummary
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.
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
Rememberthataprefixoperatorchangesthevariablevalueimmediately–apostfixoperatorchangesthevaluesubsequently.
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.
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
Unlikethe=assignoperator,the==equalityoperatorcomparesoperandsandisdescribedhere.
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.
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
TheASCIIcodevalueforuppercase“A”is65,butforlowercase“a”it’s97–sotheircomparisonherereturnsfalse(0).
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.
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;
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”.
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.
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
Theternaryoperatorcanreturnvaluesofanydatatype–numbers,strings,Booleanvalues,etc.
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.
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
Here,theintdatatypeiscreatedasalongtypebydefault–yoursystemmaybedifferent.
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
+=-=*=/=%=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;
cout<<“Default direct ion:”<<num<<endl;
Now,assigntheresultofthisexpressiontothevariableusingexplicitprecedence,thenoutputtheresultnum=7-(4+2);cout <<“Forceddirect ion:”<<num<<endl;
Save,compileandruntheprogramtoseetheoutput
Donotrelyupondefaultprecedenceasitmayvarybetweencompilers–alwaysuseparenthesestoclarifyexpressions.
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!
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
ASCII(pronounced“askee”)istheAmericanStandardCodeforoutInformationInterchange,whichistheacceptedstandardforplaintext.InASCII,charactersarerepresentednumericallywithintherange0-127.Uppercase‘A’is65,sothatintegervaluegetscastintoanintvariable.
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.
3
Makingstatements
ThischapterdemonstratesC++conditionalstatements,whichallowprogramstobranchindifferentdirections,and
introducesC++functionstructures.
BranchingwithifSwitchingbranchesLoopingforLoopingwhileDeclaringfunctionsPassingargumentsOverloadingfunctionsOptimizingfunctionsSummary
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>
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
ShorthandcanbeusedwhentestingaBooleanvalue–sotheexpressionif(flag==true)canbewrittenasif(flag).
Avoidnestingmorethanthreelevelsofifstatements–toavoidconfusionanderrors.
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.
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;
Noticethatadefaultstatementdoesnotneedtobefollowedbyabreakkeyword–becauseadefaultstatementalwaysappearslastinaswitchstatement.
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;
}
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
decrementingtheiterationusingi--insteadofthei++incrementer.
Onthethirditerationoftheseloops,theincrementerincreasesthecountervaluetofour–sowhenitisnextevaluated,thetestreturnsfalseandtheloopends.
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;
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
Thevectorlibrarymustbeincludedwithapreprocessordirectiveinthisexample.
Thepositionofbreakandcontinuestatementsisimportant–theymustappearaftertheincrementer,toavoidcreatinganinfiniteloop,butbeforeotherstatementsthataffecttheprogramtoavoidexecutingthosestatements.
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.
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;
}
float bodyTempF(){
float temperature=98.6;returntemperature;
}
Save,compile,andruntheprogramtoseetheoutput
Variablesofthesamenamedonotconflictwhentheyaredeclaredinadifferentscope–theyarenotvisibletoeachother.
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;
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
Inthesamewaythatfunctionscanbecalledfromthemainfunction,functionsmaycallotherfunctionsandpassargumentstothem.
Thenamesgiventotheargumentsandvariablesinthefunctiondefinitiondonotneedtobethesameasthevariablenamesinthecallingfunction–butithelpstoclarifytheprogram.
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));
}
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
Thevaluepassedtothecharargumentisneverused–thatargumentisincludedmerelytodifferentiatethatoverloadedfunction.
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.
}
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.
Inlinedeclarationsmayonlycontainoneortwostatements,asthecompilerrecreatesthemateachcallingpoint–longerinlinedeclarationswould,therefore,produceamoreunwieldyprogram.
Deletethefactorial()functiondefinition,thenreplaceitsprototypedeclarationwiththisinlinedeclarationinlineint factorial(int n){return(n==1)?1:(factorial(n-1)*n);}
Save,compile,andruntheprogramagaintoseethesameoutput,producedmoreefficiently
Summary• AnifstatementevaluatesagiventestexpressionforaBooleanvalueoft rueorfalse.
• Statementscontainedinbracesafteranifstatementwillonlybeexecutedwhentheevaluationisfoundtobet rue.
• Theifandelsekeywordsareusedtoperformconditionalbranchingaccordingtotheresultofatestedexpression.
• Aswitchstatementisanalternativeformofconditionalbranchingthatmatchesacasestatementtoagivenvalue.
• Theforloopstructurehasparametersdeclaringaninitializer,atestexpression,andanincrementerordecrementer.
• Awhileloopanddo-whileloopmustalwayshaveanincrementerordecrementerwithintheirloopbody.
• Anytypeofloopcanbeimmediatelyterminatedbyincludingabreakstatementwithintheloopbody.
• Asingleiterationofanytypeofloopcanbeskippedbyincludingacont inuestatementwithintheloopbody.
• Functionsareusuallydeclaredasprototypesatthestartoftheprogram,anddefinedafterthemainfunction.
• Variablesdeclaredinafunctionareonlyaccessiblefromwithinthatfunction,astheyonlyhavelocalscope.
• Valuescanbepassedintofunctionsifargumentsaredeclaredinthefunctionprototypeanddefinition.
• Overloadedfunctionshavethesamenamebutadifferentnumberortypeofdeclaredarguments.
• Recursivefunctionsrepeatedlycallthemselvesuntilatestconditionismet.
• Shortfunctiondefinitionsofjustoneortwostatementscanbedeclaredinplaceofaprototypeusingtheinlinekeyword.
4
Handlingstrings
ThischapterdemonstrateshowtomanipulateC++textstringsasasimpler,morepowerfulalternativetocharacter
arrays.
CreatingstringvariablesGettingstringinputSolvingthestringproblemDiscoveringstringfeaturesJoining&comparingstringsCopying&swappingstringsFindingsubstringsReplacingsubstringsSummary
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.
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
Remembertoaddthespecial\0charactertomarktheendofastringinachararray.
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;
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.
Theargumentstothecin.ignore()functionspecifyitshoulddiscardupto256charactersandstopwhenitencountersanewlinecharacter.
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.
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.
Anon-emptystringstreamobjecthasbitflagsindicatingitsstatusasgood,bad,eof,orfail–theseshouldbeclearedbeforere-usebythestringstreamobject’sclear()function,asdemonstratedhere.
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()
{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
Theempty()functionisusefultocheckiftheuserhasenteredrequestedinput.
Aspaceoccupiesonememoryelement–justlikeacharacterdoes.
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;
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.
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);
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.
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
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.
Thefirstcharacterinastringisatpositionzero,notatpositionone.
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
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
thepositioninthesubstringatwhichtobegincopying,andthenumberofcharacterstobecopied.
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.
5
Readingandwritingfiles
Thischapterdemonstrateshowtostoreandretrievedataintextfiles,andillustrateshowtoavoiderrorsinC++
programs.
WritingafileAppendingtoafileReadingcharacters&linesFormattingwithgetlineManipulatinginput&outputPredictingproblemsRecognizingexceptionsHandlingerrorsSummary
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.
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.
Stringvaluescancontain\nnewlineand\ttabescapesequencesforformattinglines.
Noticehowthenewlineandtabcharactersarepreservedinthetextfile.
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.
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.
Thefilemustallowtheprogramsuitablereadandwritepermissions.
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();
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;
Outputanendlaftereachlineoutput–becausegetline()stopsreadingwhenitmeetsa\nnewlinecharacter.
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;
}
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
Theifstatementtestsiftheitemnumber(elementnumberplus1)isexactlydivisiblebyfour,todeterminewhethertoreaduptoanewlineortabcharacter.
Therecordcountermustuseaprefixincrementertoincreasethevariablevaluebeforeitisoutput.
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
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
formatscout <<isTrue<<“:”<<boolalpha<<isTrue<<endl;cout <<num<<“:”<<hex<<showbase<<uppercase<<num<<endl;
Save,compile,andruntheprogramtoseetheoutput
Manipulatorsaffectallinputoroutputonthatstream.Forexample,theboolalphamanipulatorwilldisplayallBooleanvaluesonthatstreaminwrittenform.
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.
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
Whenanexceptionoccurs,controlpassestothecatchblock–inthisexample,theloopdoesnotcomplete.
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
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
exceptionthrowntoacatchblock.
Thespecificexceptionclassnamecanappear,inplaceofthegeneralexcept iontype,withinthecatchblock’sparentheses.
Theexampledescribedheredemonstratestheuseofstandardexceptions.
Multiplecatchblockscanbeusedinsuccession,muchlikecasestatementsinaswitchblock,tohandleseveraltypesofexception.
Additionally,exceptionscanbeproducedmanuallybythethrowkeyword.Thiscanbeusedtocreateanyofthelogic_errorandrunt ime_errorexceptionsinthetableabove.Optionally,acustomerrormessagecanbespecifiedformanualexceptions,whichcanberetrievedbyitswhat ()function.
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;
}
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
Theorderofcatchblockscanbeimportant–placingtheexceptionerrorhandlerbeforetheout_of_rangeerrorhandlerwouldallowanout_of_rangeerrortobehandledbythe(higherlevel)exceptionhandler.
Anexceptionobjectistypicallygiventhename“e”–asseenhere.
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.
6
Pointingtodata
ThischapterdemonstrateshowtoproduceefficientC++programs,utilizingpointersandreferences.
UnderstandingdatastorageGettingvalueswithpointersDoingpointerarithmeticPassingpointerstofunctionsMakingarraysofpointersReferencingdataPassingreferencestofunctionsComparingpointers&referencesSummary
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
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
L-valuesarecontainersbutR-valuesaredata.
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.
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.
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;
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.
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=#
Afterthemainfunctionblock,defineafunctiontooutputthecurrentvalueofa
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.
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”};
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
Toincludeaspaceinachararray,theassignmentmusthaveaspacebetweenthequotesas‘‘–twosinglequotestogether(‘‘)isregardedasanemptyelementandcausesacompilererror.
Rememberthatthefinalelementofachararraymustcontainthespecial\0charactertodesignatethatarrayasastring.
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
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.
Areferenceisalwaysanaliasfortheitemassociatedinitsdeclarationstatement.
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;
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
Thefunctionprototypeanddefinitionmustbothcontainareferenceargument.
Functionsthatoperatedirectlyonvariableswithinthecallingfunctionneednoreturnstatement.
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.
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=#void(*fn)(int&a,int *b)=add;//Addmorestatementshere.return0;
}
Inthemainfunction,insertstatementstooutputthefirstintegervariablevaluesviathereferenceandpointercout <<“Reference:”<<rNum<<endl;cout <<“Pointer:”<<*pt r<<endl;
Now,assignthesecondintegervariabletothepointerandoutputitsvalueviathepointer,thencallthefunctionpointertooutputthesumofthevariablevaluespt r=∑cout <<“Pointernow:”<<*pt r<<endl;fn(rNum,pt r);
Save,compile,andruntheprogramtoseetheoutput
Cprogrammerstendtoputthe&and*charactersbeforethevariablenames,butinC++itisusualtoputthemafterthedatatype–asthefeatureisapropertyofthedatatype,notthename.
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.
7
Creatingclassesandobjects
Thischapterintroducesthetopicsofencapsulationandinheritance–thefirsttwoprinciplesofC++ObjectOriented
Programming.
EncapsulatingdataCreatinganobjectCreatingmultipleobjectsInitializingclassmembersOverloadingmethodsInheritingclasspropertiesCallingbaseconstructorsOverridingbasemethodsSummary
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.
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{
int age,weight ;st ringcolor;
public:voidbark();//...Plusmethodstostore/ret rievedata.
}fido,pooch,rex,sammy;
TheprincipleofencapsulationinC++programmingdescribesthegroupingtogetherofdataandfunctionalityinclassmembers–age,weight,colorattributesandbarkactionintheDogclass.
Itisconventionaltobeginclassnameswithanuppercasecharacterandobjectnameswithlowercase.
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;}
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
Fido
Thisprogramwillgetmodifiedoverthenextfewpagesasnewfeaturesareincorporated.
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.
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
Wheretheargumentnameandclassmembernamesaredifferent,thethis->classpointerisnotneededinthesettermethoddefinitions.
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;
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”.
Althoughtheinitialvaluesofthevariablemembersaresetbytheconstructor,settermethodscanbeaddedtosubsequentlychangethevalues–andthosenewvaluescanberetrievedbythegettermethods.
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”;
}
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
Don’taddparenthesesaftertheobjectnamewhencreatinganobjectwithoutpassingarguments–noticeit’sDogrex;notDogrex();
ThisisthefinalrenditionoftheDogclass.Besureyoucanreadilyidentifyitspublicandprivatemembersbeforeproceeding.
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
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
Don’tconfuseclassinstancesandderivedclasses–aninstanceisacopyofaclass,whereasaderivedclassisanewclassthatinheritspropertiesofthebaseclassfromwhichitisderived.
Aclassdeclarationcanderivefrommorethanoneclass.Forexample,classBox:publicA,publicB,publicC{};.
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{
};
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
NoticethatthesyntaxintheoverloadedSonclassconstructorpassestheintegerargumenttotheoverloadedbaseclassconstructor.
Eachclassautomaticallyhasanemptydefaultconstructoranddestructor–forexample,Son(){}and~Son(){}.
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.};
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
HenryandEnrique
Theoverridingmethoddeclaredinthederivedclasshidesbothoverloadedclassesinthebaseclass.Trycallingenrique.speak()–thecompilerwillcomplainthereisnomatchingmethodforthatcall.
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.
8
Harnessingpolymorphism
Thischapterdemonstrateshowtoseparateprogramsintomodularcomponentsandintroducesthetopicofpolymorphism
–thethirdprincipleofC++ObjectOrientedProgramming.
PointingtoclassesCallingavirtualmethodDirectingmethodcallsProvidingcapabilityclassesMakingabstractdatatypesBuildingcomplexhierarchiesIsolatingclassstructuresEmployingisolatedclassesSummary
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.
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
The->classpointeroperatorisusedheretocallclassmethods.
Thehexadecimaladdressispassedasanintdatatype,thendisplayedinhexadecimalformatbythehexoutputmanipulator.Theaddresseswillbedifferenteachtimetheprogramexecutes–theyareassigneddynamically.
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;}
};
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.
Save,compile,andruntheprogramtoseetheoutput
Here,theGrandchildclassinheritsthepropertiesoftheChildclass,whichinheritsthepropertiesoftheParentclass.
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;}
};
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
Thebackslash\characterisrequiredtoescapetheapostropheinstrings.
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;}
};
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
Capabilityclassmethodsareintendedtobeoverriddeninderivedclasses–theyshouldnotbecalledexplicitly.
Referbacktohereformoredetailsonerrorhandling.
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 ();
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;
AbaseclassneedonlycontainonepurevirtualmethodtocreateanAbstractDataType.
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:
};
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
TryaddingaPowerboatclassderivedfromtheBoatclass(tocontainengineinformation),andaCruiserclassderivedfromthePowerboatclass–toassignvariablevaluesandtodefinevirtualmethods.
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).
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.
charoper;//Tostoreinput operator.boolstatus;//Tostorecurrent status.
Savetheheaderfileas“ops.h”
Turntothenextpagetocontinuethisexamplebycreatinganimplementationfile–containingdefinitionsfortheCalculatorclassmethodsdeclaredinthe“ops.h”headerfile
Noticethattheheaderfilenamemustbesurroundedbyquotesinan#includedirective–notbythe<>angledbracketsusedtoincludeastandardC++library.
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;}
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
ThisprogramloopsuntiltheusertypesazeroandhitsReturn–changingthe“status”controlvariabletofalse,andsoexitingtheprogram.
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.
9
Processingmacros
ThischapterdemonstrateshowtheC++compilercanbemadetoperformusefultasksbeforecompilingaprogram.
ExploringcompilationDefiningsubstitutesDefiningconditionsProvidingalternativesGuardinginclusionsUsingmacrofunctionsBuildingstringsDebuggingassertionsSummary
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
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
programtoseethemessagec++prog.o-oprog.exe
Oneormoreobjectfilescanbeusedtocreateanexecutablefile–asdescribedhere.
Youcancombinethesesteps,creatinganexecutablefileandsavingtemporaryfiles,byissuingthecommandc++prog.cpp-save-temps-oprog.exe.
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
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.
Delete,orcomment-out,thedefinedirectivesforboththeBOOKandNUMidentifiers–thensavetheprogramfiletoapplythechanges
Recompiletheprogram,specifyingsubstitutemacrovalues,thenruntheprogramoncemorec++-DNUM=50-DBOOK=\””XMLineasysteps”\”define.cpp-odefine.exe
Attemptingtocompileaprograminwhichanidentifierhasnotbeendefinedwillproducea“notdeclaredinthisscope”error.
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
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.
OnWindowssystems,stringmacrovaluesspecifiedinacommandmustbeenclosedinescapeddoublequotes.
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
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
Thepredefined_WIN32macrohasoneunderscorebutthe__linuxmacrohastwounderscorecharacters.
Theconditionaltestofpredefinedmacroscouldbeextendedtoseekthoseofotheroperatingsystems,andafinal#elsedirectiveaddedtospecifyan“Unknown”default.
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
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
Usetheconventionalnamingscheme,wherethemacronameresemblesthefilename,toavoidconflicts.
Allheaderfilesshouldcontainheaderguards–addaTRIPLE_Hmacrotothet riple.hfile.
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
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.
Aninlinefunctionsavestheoverheadofcheckingbetweenafunctionprototypedeclarationanditsdefinition.
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”;
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.
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) \
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
Predefinedmacronamesareprefixedbyadouble-underscoreandsuffixedbyadouble-underscore.
Additionally,thecurrentdateandtimecanbeoutputfromthe__DATE__and__TIME__predefinedmacros.
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.
10
Programmingvisually
ThischapterbringstogetherelementsfrompreviouschapterstobuildacompleteC++applicationinavisual
programmingenvironment.
StartingaUniversalprojectInsertingpagecomponentsImportingprogramassetsDesigningthelayoutAddingruntimefunctionTestingtheprogramAdjustingtheinterfaceDeployingtheapplicationSummary
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
Afterinstallationofthetools,opentheVisualStudioIDE
AUWPapplicationisalsoknownasa“UWA”–UniversalWindowsApplication.
DependinguponyourchoiceswhenyouinstalledVisualStudio,youmayseetheoptionscheckedwhentheinstallerlaunches,toindicateyoualreadyhavetheUniversalWindowsAppDevelopmentTools.
Next,selectFile,New,ProjectandcreateanewBlankApp(UniversalWindows)projectcalled“Universal”
Whenaskedtoselectthetargetandminimalplatformversions,simplyclickOKtoacceptthedefaultoptions
AfterVisualStudiocreatesthenewproject,selectView,SolutionExplorertoexaminethegeneratedfiles:
• AsetoflogoimagesinanAssetsfolder
• InternalXAMLandC++Appfiles
• XAMLandC++filesfortheMainPage–hereiswhereyouwillcreateinterfacecomponentsandfunctionalcode
• OthermiscellaneousPackagefiles
InWindows10,youshouldensurethattheDeveloperModeoptionisenabledinSettings,Update&Security,Fordevelopers.
ThesefilesareessentialtoallUWPappsusingC++,andexistineveryprojectVisualStudiocreatestotargettheUniversalWindowsPlatformwithC++.
InsertingpagecomponentsVisualStudioprovidesatwo-partwindowtoinsertinterfacecomponentsintoaUWPapp.ThiscomprisesaDesignviewofthecomponentsandaXAMLviewfortheXAMLcode:
Universal
OpenSolutionExplorerthendouble-clickonMainPage.xaml–tolaunchthetwo-partwindow
Seethatbydefault,theDesignviewdisplaysablankcanvasinPortraitmode
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:
AsyouaddthecomponentelementsinXAMLview,theyappearintheDesignviewuntilitlookslikethis:
Thex:prefixbeforetheNameattributereferstotheXAMLschemausedbyUWPapps.
Theouter<StackPanel>isahorizontallayoutcontainingan<Image>andanested<Stackpanel>.Thenested<StackPanel>isaverticallayoutcontainingtwofurther<StackPanel>elementsthateachdisplaytheircomponentshorizontally.
Noticethateach<TextBlock>elementhasaText attributethatcanbereferencedinfunctionalcode.E.g.t extBlock1->Text .
ImportingprogramassetsInordertohaveaXAML<Image>componentdisplayagraphic,animagefilefirstneedstobeaddedtotheproject’sAssetsfolder.ItcanthenbeassignedtoaSourceattributeofthe<Image>tag:
Universal
OpenSolutionExplorer,thenright-clickontheAssetsfolderandchooseAddfromthecontextmenu
Now,chooseExistingItemfromthenextcontextmenu–toopenanAddExistingItemdialogbox
IntheAddExistingItemdialog,browsetothelocationofanimagethenselectthefileandclicktheAddbutton
Animagefordisplaymaybeinanypopularfileformat–suchas.bmp,.gif,.jpg,.png,or.t if.
InSolutionExplorer,theselectedimagefilenowappearsintheproject’sAssetfolder
SelecttheImagecomponentinDesignerview,thenclickView,Propertiestorevealitsproperties
InthePropertieswindow,expandtheCommoncategory,thenclicktheSourceitem’sarrowbuttonandselecttheaddedimagefromthedrop-downlist
TheimagenowappearsintheDesignview,anditspathgetsaddedtotheXAMLviewcodeandSourceproperty
ExploretheAppearanceandTransformoptionsinanimage’sPropertieswindowtodiscoverhowyoucanmodifyhowitwillbedisplayed.
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
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
grayedout,asitisnotenabled.
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
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:
ReturntotheMainPage.xamlfile,theninXAMLview,seethatattributeshavebeenautomaticallyaddedtothe<But ton>elementstocalltheevent-handlercode
Noticethatthefirstforloopcontainsonlyonestatementtobeexecutedoneachiteration,sobracesarenotrequired.
TestingtheprogramHavingaddedfunctionalitywithC++codeabove,youarenowreadytotesttheprogramfortwodevices:
Universal
OntheVisualStudiostandardtoolbar,selectDebugforx64architectureandLocalMachineoptions,thenclicktheStartbuttontoruntheappforaPCdevice
Waitwhiletheapplicationgetsbuiltandloaded,thenclickthebuttonstotryouttheirfunctionality
YoumusthaveyourPCsettoDeveloperModeinSettings,Update&Security,Fordevelopers.
TheapplooksgoodonPCdevices–numbersarebeingrandomizedandthebuttonstatesarechangingasrequired.
Now,ontheVisualStudiostandardtoolbar,selectDebug,StopDebuggingtoexittherunningprogram
YoucansafelyignoretheDEBUGnumbersthatappearintheblackboxes,butifyouprefernottoseethem,selectProject,ProjectNameProperties,BuildthenunchecktheDefineDEBUGconstantoption.
OntheVisualStudiostandardtoolbar,selectDebugforx86architectureandsmallMobileEmulatoroptions,thenclicktheStartbuttontoruntheappforamobiledevice
Waitwhiletheemulatorstartsup–thistakesawhile
Whentheapplicationgetsbuiltandloaded,youseethecontrolsarenotvisible–soyoucan’ttryouttheirfunctionality!
What’sgoingonhere?Clickoneoftheemulator ’sRotatebuttonstoflipitovertoLandscapeorientationandlookforclues
Ah-ha!Someofthecontrolsarenowvisible,butthisisunsatisfactory–adjustmentswillbeneededtotheinterfacelayoutsotheapplooksgoodonmobiledevices
Again,ontheVisualStudiostandardtoolbar,selectDebug,StopDebuggingtoexittherunningprogram
Testontheemulatorwithlowestmemoryandsmallestscreenanditshouldbefinerunningonthoseemulatorswithbetterfeatures.
DonotclicktheXbuttonontheemulatorwindowtostoptherunningprogram,asthatwillalsoclosetheemulator.
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:
XAMLcoderecognizesthesame<!---->commenttagsthatareusedinHTMLcode.
Rememberthattheouter<StackPanel>inthisappcontainsan<Image>andanested<StackPanel>displayedhorizontally,side-by-side.Ifdisplayedvertically,theyshouldappearoneabovetheother.
Selectx64andLocalMachinetoruntheappforaPCdeviceoncemore–itstilllooksandfunctionswell
Nowselectx86andMobileEmulatortoruntheappforamobiledevice–italsonowlooksandfunctionswell
YoucanhaveVisualStudionicelyformattheXAMLcodebypressingCtrl+K,Ctrl+D.
Althoughanappmayworkwellonanemulator,itisrecommendedyoualwaystestonactualdevicesbeforedeployment.
DeployingtheapplicationHavingtestedtheappinaMobileEmulatorabove,itcannowbetestedonarealdevicebeforedeployment:
Universal
OnaWindows10deviceselectDevelopermodefromtheSettings,Update&Security,Fordevelopersmenu
Next,connectthedevicetoyourPCviaaUSBsocket
OntheVisualStudiotoolbar,selectDebugforARMarchitectureandDeviceoptions,thenclicktheStartbuttontoruntheappontheconnecteddevice
Waitwhiletheapplicationgetsbuiltandloaded,thentapthebuttonstotryouttheirfunctionality
YoucanchoosetheRemoteMachineoptiontotestviaanetworkconnection.
Theapplooksgood,numbersarebeingrandomized,andthebuttonstatesarechangingasrequired–theappcanbedeployed.
RemovetheDebugversionoftheappfromthedevice
InSolutionExplorer,addlogoimagestotheAssetsfolder,thendouble-clickonPackage.appmanifestandaddthemtoVisualAssets
AddthreelogoimagestotheAssetsfolderoftherequiredsizes,thenclickthese
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
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.