Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Download
Standard view
Full view
of .
Look up keyword
Like this
0Activity
0 of .
Results for:
No results containing your search query
P. 1
A Quick Introduction to C++

A Quick Introduction to C++

Ratings: (0)|Views: 4 |Likes:
Published by Thusith Alexander

More info:

Published by: Thusith Alexander on Nov 10, 2012
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

11/10/2012

pdf

text

original

 
AQuickIntroductiontoC+
TomAndersobasedonanearlierversionwrittenbyWayneChristopheAugust30,199
\IfprogramminginPascalislikebeingputinastraightjacket,thenprogramminginCislikeplayingwithknives,andprogramminginC++islikejuggling chainsaws.Anonymous
1Introductio
ThisnoteintroducessomesimpleC++conceptsandoutlinesasubsetofC++thatiseasietolearnandusethanthefulllanguage.ItistargetedtothosejustlearningC++,buteveifyoualreadyknowthelanguage,youmightndituseful.Iassumethatyouarealready somewhatfamiliarwithCconceptslikeprocedures,forloops,andpointersthesearepretteasytopickupfromreadingKernighanandRitchie'sCbookKR80]IshouldadmitupfrontthatIamquiteopinionatedaboutC++,ifthatisn'tobvioualready.IknowseveralC++purists(anoxymoronperhaps?)whoviolentlydisagreewitsomeoftheprescriptionscontainedheremostoftheobjectionsareoftheform,\HowcoulyouhavepossiblyleftoutfeatureX?"However,I'vefoundfromteachingC++tonearl1000undergradsoverthepastseveralyearsthatthesubsetofC++describedhereispretteasytolearn,takingonlyadayorsoformoststudentstogetstarted. Thebasicpremiseofthisnoteisthatwhileobject-orientedprogrammingisausefulway tosimplifyprograms,C++isawildlyover-complicatedlanguage,withahostoffeaturethatonlyvery,veryrarelyndalegitimateuse.It'snottoofarothemarktosaythaC++includeseveryprogramminglanguagefeatureeverimagined,andmore.Thenaturatendencywhenfacedwithanewlanguagefeatureistotrytouseit,butinC++thiapproachleadstodisasterThus,weneedtocarefullydistinguishbetween(i)thoseconceptsthatarefundamental (e.g.,classes,memberfunctions,constructors){onesthateveryoneshouldknowanduse(ii)thosethataresometimesbutrarelyuseful(e.g.,singleinheritance,templates){ones thatbeginnerprogrammersshouldbeabletorecognize(incasetheyrunacrossthem)but avoidusingintheirownprograms,atleastforawhile,and(iii)thosethatarejustabadidea andshouldbeavoidedliketheplague(e.g.,multipleinheritance,exceptions,overloading, references,etc)
 
Ofcourse,alltheitemsinthislastcategoryhavetheirproponents,andIwilladmitthatlikethehatedgoto,itispossibletoconstructcaseswhentheprogramwouldbesimpleusingagotoormultipleinheritance.However,itismybeliefthatmostprogrammerswilneverencountersuchcases,andevenifyoudo,youwillbemuchmorelikelytomisusethe featurethanproperlyapplyit.Forexample,Iseriouslydoubtanundergraduatewouldneeanyofthefeatureslistedunder(iii)foranycourseproject(atleastatBerkeleythisistrue)Andifyoundyourselfwantingtouseafeaturelikemultipleinheritance,then,myadviceitofullyimplementyourprogrambothwithandwithoutthefeature,andchoosewhicheveissimpler.Sure,thistakesmoreeort,butprettysoonyou'llknowfromexperiencewhenfeatureisusefulandwhenitisn't,andyou'llbeabletoskipthedualimplementation. Areallygoodwaytolearnalanguageistoreadclearprogramsinthatlanguage.IhavtriedtomaketheNachoscodeasreadableaspossibleitiswritteninthesubsetofC+describedinthisnote.Itisagoodideatolookovertherstassignmentasyoureadthiintroduction.Ofcourse,yourTA'swillansweranyquestionsyoumayhaveYoushouldnotneedabookonC++todotheNachosassignments,butifyouarcurious,thereisalargeselectionofC++booksatCody'sandothertechnicalbookstores(MywifequipsthatC++wasinventedtomakeresearchersatBellLabsrichfromwriting "HowtoPrograminC++"books.)Mostnewsoftwaredevelopmentthesedaysisbeing doneinC++,soitisaprettygoodbetyou'llrunacrossitinthefuture.Inmyopinion, Stroustrup's"TheC++ProgrammingLanguage"isbestasareferencemanual,althougotherbooksmaybemorereadable.Coplien's"AdvancedC++Concepts"isprobablywortreading,butonlyonceyou'vebeenprogramminginC++foracoupleyearsandarefamiliar withthelanguagebasics.Also,C++iscontinuallyevolving,sobecarefultobuybooksthat describethelatestversion(currently3.0,Ithink!)
2CinC+
Toalargeextent,C++isasupersetofC,andmostcarefullywrittenANSICwillcompilasC++.Thereareafewmajorcaveatsthough: 1.Allfunctionsmustbedeclaredbeforetheyareused,ratherthandefaultingtotype 
in
2.Allfunctiondeclarationsanddenitionheadersmustusenew-styledeclarations,e.g.
externintfoo(inta,char*b) 
Thefor
externintfoo() 
meanstha
fo
takes 
n
arguments,ratherthanargu- mentsofanunspeciedtypeandnumber.Infact,someadviseusingaC++compileevenonnormalCcode,becauseitwillcatcherrorslikemisusedfunctionsthatanormal Ccompilerwillletslide. 3.IfyouneedtolinkCobjectlestogetherwithC++,whenyoudeclaretheCfunctions fortheC++les,theymustbedonelike 
 
extern"C"intfoo(inta,char*b) 
OtherwisetheC++compilerwillalterthenameinastrangemanner4.Thereareanumberofnewkeywords,whichyoumaynotuseasidentiers|somcommononesar
ne
delete 
const 
,and 
class 
3BasicConcept
BeforegivingexamplesofC++features,Iwillrstgooversomeofthebasicconceptsoobject-orientedlanguages.Ifthisdiscussionatrstseemsabitobscure,itwillbecomclearerwhenwegettosomeexamples1
Classesandobject
.Aclassdenesasetofobjects,or 
instances 
ofthatclass.One declaresaclassinawaysimilartoa
structure 
,andthencreatesobjectsofthatclassAclassdenestwoaspectsoftheobjects:the 
dat
theycontain,andthe 
behavio
they have. 2
Memberfunctions 
.Thesearefunctionswhichareconsideredpartoftheobjectand aredeclaredintheclassdenition.Theyareoftenreferredtoas 
method
oftheclassInadditiontomemberfunctions,aclass'sbehaviorisalsodenedby: (a)Whattodowhenyoucreateanewobject(the 
constructor 
forthatobject){iotherwords,initializetheobject'sdata. (b)Whattodowhenyoudeleteanobject(the 
destructor 
forthatobject)3
Privatevs.publicmember
.Apublicmemberofaclassisonethatcanbereaorwrittenbyanybody,inthecaseofadatamember,orcalledbyanybody,inthe caseofamemberfunction.Aprivatemembercanonlyberead,written,orcalledby amemberfunctionofthatclassClassesareusedfortwomainreasons:(1)itmakesitmucheasiertoorganizeyour programsifyoucangrouptogetherdatawiththefunctionsthatmanipulatethatdata,and (2)theuseofprivatemembersmakesitpossibletodo 
informationhiding 
,sothatyoucabemorecondentaboutthewayinformationowsinyourprograms
3.1Classe
C++classessimilartoCstructuresinmanyways.Infact,aC++structisreallyaclasthathasonlypublicdatamembers.Inthefollowingexplanationofhowclasseswork,wwilluseastackclassasanexample1
Memberfunctions
Hereisa(partial)exampleofaclasswithamemberfunction andsomedatamembers

You're Reading a Free Preview

Download
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->