Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ (OOP) Tutorial

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Structureofaprogram(SimpleC++program) BasicInput/Output Namespaces ExamplewithClass Structures OtherDataTypes

Structureofaprogram(SimpleC++program)
Probablythebestwaytostartlearningaprogramminglanguageisbywritingaprogram.Therefore,hereis ourfirstprogram: 1 2 3 4 5 6 7 8 9 10
// my first program in C++
#include <iostream> using namespace std;

int main () { cout << "Hello World!"; return 0; }

Hello World!

Thefirstpanel(inlightblue)showsthesourcecodeforourfirstprogram.Thesecondone(inlightgray) showstheresultoftheprogramoncecompiledandexecuted.Totheleft,thegreynumbersrepresenttheline numbersthesearenotpartoftheprogram,andareshownheremerelyforinformationalpurposes. Thewaytoeditandcompileaprogramdependsonthecompileryouareusing.Dependingonwhetherithas aDevelopmentInterfaceornotandonitsversion.Consultthecompilerssectionandthemanualorhelp includedwithyourcompilerifyouhavedoubtsonhowtocompileaC++consoleprogram. Thepreviousprogramisthetypicalprogramthatprogrammerapprenticeswriteforthefirsttime,andits resultistheprintingonscreenofthe"HelloWorld!"sentence.Itisoneofthesimplestprogramsthatcanbe writteninC++,butitalreadycontainsthefundamentalcomponentsthateveryC++programhas.Weare goingtolooklinebylineatthecodewehavejustwritten: // my first program in C++

Thisisacommentline.Alllinesbeginningwithtwoslashsigns(//)areconsideredcommentsanddo nothaveanyeffectonthebehavioroftheprogram.Theprogrammercanusethemtoincludeshort explanationsorobservationswithinthesourcecodeitself.Inthiscase,thelineisabriefdescriptionof whatourprogramis. #include <iostream> Linesbeginningwithahashsign(#)aredirectivesforthepreprocessor.Theyarenotregularcodelines withexpressionsbutindicationsforthecompiler'spreprocessor.Inthiscasethedirective#include <iostream>tellsthepreprocessortoincludetheiostreamstandardfile.Thisspecificfile(iostream) includesthedeclarationsofthebasicstandardinputoutputlibraryinC++,anditisincludedbecauseits functionalityisgoingtobeusedlaterintheprogram. using namespace std; AlltheelementsofthestandardC++libraryaredeclaredwithinwhatiscalledanamespace,the namespacewiththenamestd.Soinordertoaccessitsfunctionalitywedeclarewiththisexpression thatwewillbeusingtheseentities.ThislineisveryfrequentinC++programsthatusethestandard library,andinfactitwillbeincludedinmostofthesourcecodesincludedinthesetutorials. int main () Thislinecorrespondstothebeginningofthedefinitionofthemainfunction.Themainfunctionisthe pointbywhereallC++programsstarttheirexecution,independentlyofitslocationwithinthesource code.Itdoesnotmatterwhetherthereareotherfunctionswithothernamesdefinedbeforeorafterit theinstructionscontainedwithinthisfunction'sdefinitionwillalwaysbethefirstonestobeexecuted inanyC++program.Forthatsamereason,itisessentialthatallC++programshaveamainfunction. Thewordmainisfollowedinthecodebyapairofparentheses(()).Thatisbecauseitisafunction declaration:InC++,whatdifferentiatesafunctiondeclarationfromothertypesofexpressionsarethese parenthesesthatfollowitsname.Optionally,theseparenthesesmayenclosealistofparameterswithin them. Rightaftertheseparentheseswecanfindthebodyofthemainfunctionenclosedinbraces({}).What iscontainedwithinthesebracesiswhatthefunctiondoeswhenitisexecuted. cout << "Hello World!"; ThislineisaC++statement.Astatementisasimpleorcompoundexpressionthatcanactuallyproduce someeffect.Infact,thisstatementperformstheonlyactionthatgeneratesavisibleeffectinourfirst program. coutisthenameofthestandardoutputstreaminC++,andthemeaningoftheentirestatementisto insertasequenceofcharacters(inthiscasetheHello Worldsequenceofcharacters)intothe standardoutputstream(cout,whichusuallycorrespondstothescreen). coutisdeclaredintheiostreamstandardfilewithinthestdnamespace,sothat'swhyweneededto includethatspecificfileandtodeclarethatweweregoingtousethisspecificnamespaceearlierinour code. Noticethatthestatementendswithasemicoloncharacter(;).Thischaracterisusedtomarktheendof thestatementandinfactitmustbeincludedattheendofallexpressionstatementsinallC++programs (oneofthemostcommonsyntaxerrorsisindeedtoforgettoincludesomesemicolonaftera

statement). return 0; Thereturnstatementcausesthemainfunctiontofinish.returnmaybefollowedbyareturncode(inour exampleisfollowedbythereturncodewithavalueofzero).Areturncodeof0forthemainfunction isgenerallyinterpretedastheprogramworkedasexpectedwithoutanyerrorsduringitsexecution. ThisisthemostusualwaytoendaC++consoleprogram.

Youmayhavenoticedthatnotallthelinesofthisprogramperformactionswhenthecodeisexecuted.There werelinescontainingonlycomments(thosebeginningby//).Therewerelineswithdirectivesforthe compiler'spreprocessor(thosebeginningby#).Thentherewerelinesthatbeganthedeclarationofafunction (inthiscase,themainfunction)and,finallylineswithstatements(liketheinsertionintocout),whichwereall includedwithintheblockdelimitedbythebraces({})ofthemainfunction. Theprogramhasbeenstructuredindifferentlinesinordertobemorereadable,butinC++,wedonothave strictrulesonhowtoseparateinstructionsindifferentlines.Forexample,insteadof 1 int main () 2 { cout << " Hello World!"; 3 return 0; 4 } 5

Wecouldhavewritten:
int main () { cout << "Hello World!"; return 0; }

Allinjustonelineandthiswouldhavehadexactlythesamemeaningasthepreviouscode. InC++,theseparationbetweenstatementsisspecifiedwithanendingsemicolon(;)attheendofeachone, sotheseparationindifferentcodelinesdoesnotmatteratallforthispurpose.Wecanwritemanystatements perlineorwriteasinglestatementthattakesmanycodelines.Thedivisionofcodeindifferentlinesserves onlytomakeitmorelegibleandschematicforthehumansthatmayreadit. Letusaddanadditionalinstructiontoourfirstprogram: 1 2 3 4 5 6 7 8


// my second program in C++
#include <iostream> Hello World! I'm a C++ program

using namespace std; int main () { cout << "Hello World! "; cout << "I'm a C++ program";

9 10 return 0; } 11 12

Inthiscase,weperformedtwoinsertionsintocoutintwodifferentstatements.Onceagain,theseparationin differentlinesofcodehasbeendonejusttogivegreaterreadabilitytotheprogram,sincemaincouldhave beenperfectlyvaliddefinedthisway:


int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; }

Wewerealsofreetodividethecodeintomorelinesifweconsidereditmoreconvenient: 1 int main () 2 { 3 cout << 4 "Hello World!"; cout 5 << "I'm a C++ program"; 6 return 0; 7 } 8

Andtheresultwouldagainhavebeenexactlythesameasinthepreviousexamples. Preprocessordirectives(thosethatbeginby#)areoutofthisgeneralrulesincetheyarenotstatements.They arelinesreadandprocessedbythepreprocessoranddonotproduceanycodebythemselves.Preprocessor directivesmustbespecifiedintheirownlineanddonothavetoendwithasemicolon(;).

Comments
Commentsarepartsofthesourcecodedisregardedbythecompiler.Theysimplydonothing.Theirpurpose isonlytoallowtheprogrammertoinsertnotesordescriptionsembeddedwithinthesourcecode. C++supportstwowaystoinsertcomments: 1 // line comment 2 /* block comment */

Thefirstofthem,knownaslinecomment,discardseverythingfromwherethepairofslashsigns(//)is founduptotheendofthatsameline.Thesecondone,knownasblockcomment,discardseverything

betweenthe/*charactersandthefirstappearanceofthe*/characters,withthepossibilityofincluding morethanoneline. Wearegoingtoaddcommentstooursecondprogram: 1 2 3 4 5 6 7 8 9 10 11 12


/* my second program in C++ with more comments */
#include <iostream> using namespace std;

int main () { cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ program"; // prints I'm a C++ program return 0; }

Hello World! I'm a C++ program

Ifyouincludecommentswithinthesourcecodeofyourprogramswithoutusingthecommentcharacters combinations//,/*or*/,thecompilerwilltakethemasiftheywereC++expressions,mostlikely causingoneorseveralerrormessageswhenyoucompileit.

TopBasicInput/Output
Usingthestandardinputandoutputlibrary,wewillbeabletointeractwiththeuserbyprintingmessageson thescreenandgettingtheuser'sinputfromthekeyboard. C++usesaconvenientabstractioncalledstreamstoperforminputandoutputoperationsinsequentialmedia suchasthescreenorthekeyboard.Astreamisanobjectwhereaprogramcaneitherinsertorextract charactersto/fromit.Wedonotreallyneedtocareaboutmanyspecificationsaboutthephysicalmedia associatedwiththestreamweonlyneedtoknowitwillacceptorprovidecharacterssequentially. ThestandardC++libraryincludestheheaderfileiostream,wherethestandardinputandoutputstream objectsaredeclared.

StandardOutput(cout)
Bydefault,thestandardoutputofaprogramisthescreen,andtheC++streamobjectdefinedtoaccessitis cout. coutisusedinconjunctionwiththeinsertionoperator,whichiswrittenas<<(two"lessthan"signs). 1 cout << "Output sentence"; // prints Output sentence on screen // prints number 120 on screen 2 cout << 120; cout << x; // prints the content of x on screen 3

The<<operatorinsertsthedatathatfollowsitintothestreamprecedingit.Intheexamplesaboveitinserted theconstantstringOutput sentence,thenumericalconstant120andvariablexintothestandard outputstreamcout.Noticethatthesentenceinthefirstinstructionisenclosedbetweendoublequotes(") becauseitisaconstantstringofcharacters.Wheneverwewanttouseconstantstringsofcharacterswemust enclosethembetweendoublequotes(")sothattheycanbeclearlydistinguishedfromvariablenames.For example,thesetwosentenceshaveverydifferentresults: 1 cout << "Hello"; 2 cout << Hello;
// prints Hello // prints the content of Hello variable

Theinsertionoperator(<<)maybeusedmorethanonceinasinglestatement:
cout << "Hello, " << "I am " << "a C++ statement";

ThislaststatementwouldprintthemessageHello, I am a C++ statementonthescreen.The utilityofrepeatingtheinsertionoperator(<<)isdemonstratedwhenwewanttoprintoutacombinationof variablesandconstantsormorethanonevariable:


cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;

Ifweassumetheagevariabletocontainthevalue24andthezipcodevariabletocontain90064the outputofthepreviousstatementwouldbe:
Hello, I am 24 years old and my zipcode is 90064

Itisimportanttonoticethatcoutdoesnotaddalinebreakafteritsoutputunlessweexplicitlyindicateit, therefore,thefollowingstatements: 1 cout << "This is a sentence."; 2 cout << "This is another sentence.";

willbeshownonthescreenonefollowingtheotherwithoutanylinebreakbetweenthem: This is a sentence.This is another sentence. eventhoughwehadwrittenthemintwodifferentinsertionsintocout.Inordertoperformalinebreakon

theoutputwemustexplicitlyinsertanewlinecharacterintocout.InC++anewlinecharactercanbe specifiedas\n(backslash,n): 1 cout << "First sentence.\n"; 2 cout << "Second sentence.\nThird sentence.";

Thisproducesthefollowingoutput: First sentence. Second sentence. Third sentence. Additionally,toaddanewline,youmayalsousetheendlmanipulator.Forexample: 1 cout << "First sentence." << endl; 2 cout << "Second sentence." << endl;

wouldprintout: First sentence. Second sentence. Theendlmanipulatorproducesanewlinecharacter,exactlyastheinsertionof'\n'does,butitalsohasan additionalbehaviorwhenitisusedwithbufferedstreams:thebufferisflushed.Anyway,coutwillbean unbufferedstreaminmostcases,soyoucangenerallyuseboththe\nescapecharacterandtheendl manipulatorinordertospecifyanewlinewithoutanydifferenceinitsbehavior.

StandardInput(cin).
Thestandardinputdeviceisusuallythekeyboard.HandlingthestandardinputinC++isdonebyapplying theoverloadedoperatorofextraction(>>)onthecinstream.Theoperatormustbefollowedbythevariable thatwillstorethedatathatisgoingtobeextractedfromthestream.Forexample: 1 int age; 2 cin >> age;

Thefirststatementdeclaresavariableoftypeintcalledage,andthesecondonewaitsforaninputfrom cin(thekeyboard)inordertostoreitinthisintegervariable.

cincanonlyprocesstheinputfromthekeyboardoncetheRETURNkeyhasbeenpressed.Therefore,even ifyourequestasinglecharacter,theextractionfromcinwillnotprocesstheinputuntiltheuserpresses RETURNafterthecharacterhasbeenintroduced. Youmustalwaysconsiderthetypeofthevariablethatyouareusingasacontainerwithcinextractions.If yourequestanintegeryouwillgetaninteger,ifyourequestacharacteryouwillgetacharacterandifyou requestastringofcharactersyouwillgetastringofcharacters. 1 2 3 4 5 6 7 8 9 10 11 12 13 14

// i/o example
#include <iostream> using namespace std;

int main () { Please enter an integer value: 702 int i; The value you entered is 702 and its dou cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0; }

Theuserofaprogrammaybeoneofthefactorsthatgenerateerrorseveninthesimplestprogramsthatuse cin(liketheonewehavejustseen).Sinceifyourequestanintegervalueandtheuserintroducesaname (whichgenerallyisastringofcharacters),theresultmaycauseyourprogramtomisoperatesinceitisnot whatwewereexpectingfromtheuser.Sowhenyouusethedatainputprovidedbycinextractionsyouwill havetotrustthattheuserofyourprogramwillbecooperativeandthathe/shewillnotintroducehis/hername orsomethingsimilarwhenanintegervalueisrequested.Alittleahead,whenweseethestringstream classwewillseeapossiblesolutionfortheerrorsthatcanbecausedbythistypeofuserinput. Youcanalsousecintorequestmorethanonedatuminputfromtheuser:


cin >> a >> b;

isequivalentto: 1 cin >> a; 2 cin >> b;

Inbothcasestheusermustgivetwodata,oneforvariableaandanotheroneforvariablebthatmaybe separatedbyanyvalidblankseparator:aspace,atabcharacteroranewline.

cinandstrings
Wecanusecintogetstringswiththeextractionoperator(>>)aswedowithfundamentaldatatype variables:
cin >> mystring;

However,asithasbeensaid,cinextractionstopsreadingassoonasiffindsanyblankspacecharacter,soin thiscasewewillbeabletogetjustonewordforeachextraction.Thisbehaviormayormaynotbewhatwe want;forexampleifwewanttogetasentencefromtheuser,thisextractionoperationwouldnotbeuseful. Inordertogetentirelines,wecanusethefunctiongetline,whichisthemorerecommendablewaytoget userinputwithcin: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

// cin with strings #include <iostream> #include <string> using namespace std; int main () { string mystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!\n"; return 0; }
What's your name? Juan Souli Hello Juan Souli. What is your favorite team? The Isotopes I like The Isotopes too!

Noticehowinbothcallstogetlineweusedthesamestringidentifier(mystr).Whattheprogramdoesin thesecondcallissimplytoreplacethepreviouscontentbythenewonethatisintroduced.

stringstream
Thestandardheaderfile<sstream>definesaclasscalledstringstreamthatallowsastringbased objecttobetreatedasastream.Thiswaywecanperformextractionorinsertionoperationsfrom/tostrings, whichisespeciallyusefultoconvertstringstonumericalvaluesandviceversa.Forexample,ifwewantto extractanintegerfromastringwecanwrite: 1 string mystr ("1204"); 2 int myint; 3 stringstream(mystr) >> myint;

Thisdeclaresastringobjectwithavalueof"1204",andanintobject.Thenweuse stringstream'sconstructortoconstructanobjectofthistypefromthestringobject.Becausewecanuse stringstreamobjectsasiftheywerestreams,wecanextractanintegerfromitaswewouldhavedone oncinbyapplyingtheextractoroperator(>>)onitfollowedbyavariableoftypeint. Afterthispieceofcode,thevariablemyintwillcontainthenumericalvalue1204. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

// stringstreams #include <iostream> #include <string> #include <sstream> using namespace std; int main () { string mystr; float price=0; int quantity=0;
cout << "Enter price: "; getline (cin,mystr); stringstream(mystr) >> price; cout << "Enter quantity: "; getline (cin,mystr); stringstream(mystr) >> quantity; cout << "Total price: " << price*quantity << endl; return 0;

Enter price: 22.25 Enter quantity: 7 Total price: 155.75

Inthisexample,weacquirenumericvaluesfromthestandardinputindirectly.Insteadofextractingnumeric valuesdirectlyfromthestandardinput,wegetlinesfromthestandardinput(cin)intoastringobject (mystr),andthenweextracttheintegervaluesfromthisstringintoavariableoftypeint(quantity). Usingthismethod,insteadofdirectextractionsofintegervalues,wehavemorecontroloverwhathappens withtheinputofnumericvaluesfromtheuser,sinceweareseparatingtheprocessofobtaininginputfrom theuser(wenowsimplyaskforlines)withtheinterpretationofthatinput.Therefore,thismethodisusually preferredtogetnumericalvaluesfromtheuserinallprogramsthatareintensiveinuserinput.

Exercise WriteasimpleC++programthatacceptstwonumbersfromuserandprintsthesumand average(hint:wehavediscussedinclass)

TopNamespaces
Namespacesallowtogroupentitieslikeclasses,objectsandfunctionsunderaname.Thiswaytheglobal scopecanbedividedin"subscopes",eachonewithitsownname. Theformatofnamespacesis: namespace identifier { entities } Whereidentifierisanyvalididentifierandentitiesisthesetofclasses,objectsandfunctionsthat areincludedwithinthenamespace.Forexample: 1 namespace myNamespace 2 { int a, b; 3 } 4

Inthiscase,thevariablesaandbarenormalvariablesdeclaredwithinanamespacecalledmyNamespace. InordertoaccessthesevariablesfromoutsidethemyNamespacenamespacewehavetousethescope operator::.Forexample,toaccessthepreviousvariablesfromoutsidemyNamespacewecanwrite: 1 myNamespace::a 2 myNamespace::b

Thefunctionalityofnamespacesisespeciallyusefulinthecasethatthereisapossibilitythataglobalobject orfunctionusesthesameidentifierasanotherone,causingredefinitionerrors.Forexample: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// namespaces #include <iostream> using namespace std; namespace first { int var = 5; } namespace second { double var = 3.1416; } int main () { cout << first::var << endl;
5 3.1416

15 16 cout << second::var << endl; return 0; 17 18 } 19

Inthiscase,therearetwoglobalvariableswiththesamename:var.Oneisdefinedwithinthenamespace firstandtheotheroneinsecond.Noredefinitionerrorshappenthankstonamespaces.

using
Thekeywordusingisusedtointroduceanamefromanamespaceintothecurrentdeclarativeregion.For example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// using #include <iostream> using namespace std; namespace first { int x = 5; int y = 10; } namespace second { double x = 3.1416; double y = 2.7183; } int main () { using first::x; using second::y; cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0; }
5 2.7183 10 3.1416

Noticehowinthiscode,x(withoutanynamequalifier)referstofirst::xwhereasyrefersto second::y,exactlyasourusingdeclarationshavespecified.Westillhaveaccesstofirst::yand second::xusingtheirfullyqualifiednames. Thekeywordusingcanalsobeusedasadirectivetointroduceanentirenamespace:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

// using #include <iostream> using namespace std; namespace first { int x = 5; int y = 10; } namespace second { double x = 3.1416; double y = 2.7183; } int main () { using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0; }
5 10 3.1416 2.7183

Inthiscase,sincewehavedeclaredthatwewereusing namespace first,alldirectusesofxandy withoutnamequalifierswerereferringtotheirdeclarationsinnamespace first. usingandusing namespacehavevalidityonlyinthesameblockinwhichtheyarestatedorinthe entirecodeiftheyareuseddirectlyintheglobalscope.Forexample,ifwehadtheintentiontofirstusethe objectsofonenamespaceandthenthoseofanotherone,wecoulddosomethinglike:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// using namespace example #include <iostream> using namespace std; namespace first { int x = 5; } namespace second { double x = 3.1416; } int main () { { using namespace first; cout << x << endl; } { using namespace second; cout << x << endl; } return 0; }

5 3.1416

Namespacealias
Wecandeclarealternatenamesforexistingnamespacesaccordingtothefollowingformat: namespace new_name = current_name;

Namespacestd
AllthefilesintheC++standardlibrarydeclareallofitsentitieswithinthestdnamespace.Thatiswhywe havegenerallyincludedtheusing namespace std;statementinallprogramsthatusedanyentity definediniostream.

TopExamplewithClass
Aclassisanexpandedconceptofadatastructure:insteadofholdingonlydata,itcanholdbothdataand

functions. Anobjectisaninstantiationofaclass.Intermsofvariables,aclasswouldbethetype,andanobjectwould bethevariable. Classesaregenerallydeclaredusingthekeywordclass,withthefollowingformat:


class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names;

Whereclass_nameisavalididentifierfortheclass,object_namesisanoptionallistofnamesfor objectsofthisclass.Thebodyofthedeclarationcancontainmembers,thatcanbeeitherdataorfunction declarations,andoptionallyaccessspecifiers. Allisverysimilartothedeclarationondatastructures,exceptthatwecannowincludealsofunctionsand members,butalsothisnewthingcalledaccessspecifier.Anaccessspecifierisoneofthefollowingthree keywords:private,publicorprotected.Thesespecifiersmodifytheaccessrightsthatthemembers followingthemacquire: privatemembersofaclassareaccessibleonlyfromwithinothermembersofthesameclassor fromtheirfriends. protectedmembersareaccessiblefrommembersoftheirsameclassandfromtheirfriends,but alsofrommembersoftheirderivedclasses. Finally,publicmembersareaccessiblefromanywherewheretheobjectisvisible.

Bydefault,allmembersofaclassdeclaredwiththeclasskeywordhaveprivateaccessforallitsmembers. Therefore,anymemberthatisdeclaredbeforeoneotherclassspecifierautomaticallyhasprivateaccess.For example: 1 class CRectangle { 2 int x, y; 3 public: void set_values (int,int); 4 int area (void); 5 } rect; 6

Declaresaclass(i.e.,atype)calledCRectangleandanobject(i.e.,avariable)ofthisclasscalledrect. Thisclasscontainsfourmembers:twodatamembersoftypeint(memberxandmembery)withprivate access(becauseprivateisthedefaultaccesslevel)andtwomemberfunctionswithpublicaccess: set_values()andarea(),ofwhichfornowwehaveonlyincludedtheirdeclaration,nottheir definition.

Noticethedifferencebetweentheclassnameandtheobjectname:Inthepreviousexample,CRectangle wastheclassname(i.e.,thetype),whereasrectwasanobjectoftypeCRectangle.Itisthesame relationshipintandahaveinthefollowingdeclaration:


int a;

whereintisthetypename(theclass)andaisthevariablename(theobject). AfterthepreviousdeclarationsofCRectangleandrect,wecanreferwithinthebodyoftheprogramto anyofthepublicmembersoftheobjectrectasiftheywerenormalfunctionsornormalvariables,justby puttingtheobject'snamefollowedbyadot(.)andthenthenameofthemember.Allverysimilartowhatwe didwithplaindatastructuresbefore.Forexample: 1 rect.set_values (3,4); 2 myarea = rect.area();

Theonlymembersofrectthatwecannotaccessfromthebodyofourprogramoutsidetheclassarexandy, sincetheyhaveprivateaccessandtheycanonlybereferredfromwithinothermembersofthatsameclass. HereisthecompleteexampleofclassCRectangle: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

// classes example #include <iostream> using namespace std; class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; }
area: 12

Themostimportantnewthinginthiscodeistheoperatorofscope(::,twocolons)includedinthedefinition ofset_values().Itisusedtodefineamemberofaclassfromoutsidetheclassdefinitionitself. Youmaynoticethatthedefinitionofthememberfunctionarea()hasbeenincludeddirectlywithinthe definitionoftheCRectangleclassgivenitsextremesimplicity,whereasset_values()hasonlyits prototypedeclaredwithintheclass,butitsdefinitionisoutsideit.Inthisoutsidedeclaration,wemustusethe operatorofscope(::)tospecifythatwearedefiningafunctionthatisamemberoftheclassCRectangle andnotaregularglobalfunction. Thescopeoperator(::)specifiestheclasstowhichthememberbeingdeclaredbelongs,grantingexactlythe samescopepropertiesasifthisfunctiondefinitionwasdirectlyincludedwithintheclassdefinition.For example,inthefunctionset_values()ofthepreviouscode,wehavebeenabletousethevariablesx andy,whichareprivatemembersofclassCRectangle,whichmeanstheyareonlyaccessiblefromother membersoftheirclass. Theonlydifferencebetweendefiningaclassmemberfunctioncompletelywithinitsclassortoincludeonly theprototypeandlateritsdefinition,isthatinthefirstcasethefunctionwillautomaticallybeconsideredan inlinememberfunctionbythecompiler,whileintheseconditwillbeanormal(notinline)classmember function,whichinfactsupposesnodifferenceinbehavior. Membersxandyhaveprivateaccess(rememberthatifnothingelseissaid,allmembersofaclassdefined withkeywordclasshaveprivateaccess).Bydeclaringthemprivatewedenyaccesstothemfromanywhere outsidetheclass.Thismakessense,sincewehavealreadydefinedamemberfunctiontosetvaluesforthose memberswithintheobject:thememberfunctionset_values().Therefore,therestoftheprogramdoes notneedtohavedirectaccesstothem.Perhapsinasosimpleexampleasthis,itisdifficulttoseeanutilityin protectingthosetwovariables,butingreaterprojectsitmaybeveryimportantthatvaluescannotbe modifiedinanunexpectedway(unexpectedfromthepointofviewoftheobject). Oneofthegreateradvantagesofaclassisthat,asanyothertype,wecandeclareseveralobjectsofit.For example,followingwiththepreviousexampleofclassCRectangle,wecouldhavedeclaredtheobject rectbinadditiontotheobjectrect:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

// example: one class, two objects #include <iostream> using namespace std; class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; }
rect area: 12 rectb area: 30

Inthisconcretecase,theclass(typeoftheobjects)towhichwearetalkingaboutisCRectangle,ofwhich therearetwoinstancesorobjects:rectandrectb.Eachoneofthemhasitsownmembervariablesand memberfunctions. Noticethatthecalltorect.area()doesnotgivethesameresultasthecalltorectb.area().Thisis becauseeachobjectofclassCRectanglehasitsownvariablesxandy,asthey,insomeway,havealsotheir ownfunctionmembersset_value()andarea()thateachusesitsobject'sownvariablestooperate. Thatisthebasicconceptofobjectorientedprogramming:Dataandfunctionsarebothmembersofthe object.Wenolongerusesetsofglobalvariablesthatwepassfromonefunctiontoanotherasparameters,but insteadwehandleobjectsthathavetheirowndataandfunctionsembeddedasmembers.Noticethatwehave nothadtogiveanyparametersinanyofthecallstorect.areaorrectb.area.Thosemember functionsdirectlyusedthedatamembersoftheirrespectiveobjectsrectandrectb.

Exercise WriteaC++programthatcontainsclassdefinitionofstudentclass.Theclasshasthree memberdata:name,ageandsex(useappropriatedatatypes)andtwomemberfunctions: setData()(assignsdatatomebervariables)anddisplayData()(displayspersondatatothe user) Note:Toaccessdataoftheclassyoushouluseonlymeberfunctions

TopDataStructures(Structures)
WeknowhowgroupsofsequentialdatacanbeusedinC(C++).Butthisissomewhatrestrictive,sincein manyoccasionswhatwewanttostorearenotmeresequencesofelementsallofthesamedatatype,butsets ofdifferentelementswithdifferentdatatypes.

Datastructures(Structures)
Adatastructureisagroupofdataelementsgroupedtogetherunderonename.Thesedataelements,known asmembers,canhavedifferenttypesanddifferentlengths.DatastructuresaredeclaredinC++usingthe followingsyntax: structstructure_name{ member_type1member_name1; member_type2member_name2; member_type3member_name3; . . }object_names; wherestructure_nameisanameforthestructuretype,object_namecanbeasetofvalididentifiers forobjectsthathavethetypeofthisstructure.Withinbraces{ }thereisalistwiththedatamembers,each oneisspecifiedwithatypeandavalididentifierasitsname. Thefirstthingwehavetoknowisthatadatastructurecreatesanewtype:Onceadatastructureisdeclared,a newtypewiththeidentifierspecifiedasstructure_nameiscreatedandcanbeusedintherestofthe programasifitwasanyothertype.Forexample: 1 2 3 4 5 6 7
struct product { int weight; float price; } ;
product apple; product banana, melon;

Wehavefirstdeclaredastructuretypecalledproductwithtwomembers:weightandprice,eachofa differentfundamentaltype.Wehavethenusedthisnameofthestructuretype(product)todeclarethree objectsofthattype:apple,bananaandmelonaswewouldhavedonewithanyfundamentaldatatype. Oncedeclared,producthasbecomeanewvalidtypenamelikethefundamentalonesint,charor shortandfromthatpointonweareabletodeclareobjects(variables)ofthiscompoundnewtype,likewe havedonewithapple,bananaandmelon. Rightattheendofthestructdeclaration,andbeforetheendingsemicolon,wecanusetheoptionalfield object_nametodirectlydeclareobjectsofthestructuretype.Forexample,wecanalsodeclarethe

structureobjectsapple,bananaandmelonatthemomentwedefinethedatastructuretypethisway: 1 struct product { 2 int weight; float price; 3 } apple, banana, melon; 4

Itisimportanttoclearlydifferentiatebetweenwhatisthestructuretypename,andwhatisanobject (variable)thathasthisstructuretype.Wecaninstantiatemanyobjects(i.e.variables,likeapple,banana andmelon)fromasinglestructuretype(product). Oncewehavedeclaredourthreeobjectsofadeterminedstructuretype(apple,bananaandmelon)we canoperatedirectlywiththeirmembers.Todothatweuseadot(.)insertedbetweentheobjectnameand themembername.Forexample,wecouldoperatewithanyoftheseelementsasiftheywerestandard variablesoftheirrespectivetypes: 1 2 3 4 5 6


apple.weight apple.price banana.weight banana.price melon.weight melon.price

Eachoneofthesehasthedatatypecorrespondingtothemembertheyreferto:apple.weight, banana.weightandmelon.weightareoftypeint,whileapple.price,banana.priceand melon.priceareoftypefloat. Let'sseearealexamplewhereyoucanseehowastructuretypecanbeusedinthesamewayasfundamental types:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

// example about structures #include <iostream> #include <string> #include <sstream> using namespace std; struct movies_t { string title; int year; } mine, yours; void printmovie (movies_t movie); int main () { string mystr;
mine.title = "2001 A Space Odyssey"; mine.year = 1968; cout << "Enter title: "; getline (cin,yours.title); cout << "Enter year: "; getline (cin,mystr); stringstream(mystr) >> yours.year; cout << "My favorite movie is:\n "; printmovie (mine); cout << "And yours is:\n "; printmovie (yours); return 0;

Enter title: Alien Enter year: 1979 My favorite movie is: 2001 A Space Odyssey (1968) And yours is: Alien (1979)

void printmovie (movies_t movie) { cout << movie.title; cout << " (" << movie.year << ")\n"; }

Theexampleshowshowwecanusethemembersofanobjectasregularvariables.Forexample,themember yours.yearisavalidvariableoftypeint,andmine.titleisavalidvariableoftypestring. Theobjectsmineandyourscanalsobetreatedasvalidvariablesoftypemovies_t,forexamplewe havepassedthemtothefunctionprintmovieaswewouldhavedonewithregularvariables.Therefore, oneofthemostimportantadvantagesofdatastructuresisthatwecaneitherrefertotheirmembers individuallyortotheentirestructureasablockwithonlyoneidentifier. Datastructuresareafeaturethatcanbeusedtorepresentdatabases,especiallyifweconsiderthepossibility ofbuildingarraysofthem:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

// array of structures #include <iostream> #include <string> #include <sstream> using namespace std;
#define N_MOVIES 3

struct movies_t { string title; int year; } films [N_MOVIES]; void printmovie (movies_t movie); int main () { string mystr; int n; for (n=0; n<N_MOVIES; n++) { cout << "Enter title: "; getline (cin,films[n].title); cout << "Enter year: "; getline (cin,mystr); stringstream(mystr) >> films[n].year; }
cout << "\nYou have entered these movies:\n"; for (n=0; n<N_MOVIES; n++) printmovie (films[n]); return 0; Enter Enter Enter Enter Enter Enter title: Blade Runner year: 1982 title: Matrix year: 1999 title: Taxi Driver year: 1976

You have entered these movies: Blade Runner (1982) Matrix (1999) Taxi Driver (1976)

void printmovie (movies_t movie) { cout << movie.title; cout << " (" << movie.year << ")\n"; }

Pointerstostructures
Likeanyothertype,structurescanbepointedbyitsowntypeofpointers:

1 2 3 4 5 6 7

struct movies_t { string title; int year; };


movies_t amovie; movies_t * pmovie;

Hereamovieisanobjectofstructuretypemovies_t,andpmovieisapointertopointtoobjectsof structuretypemovies_t.So,thefollowingcodewouldalsobevalid:
pmovie = &amovie;

Thevalueofthepointerpmoviewouldbeassignedtoareferencetotheobjectamovie(itsmemory address). Wewillnowgowithanotherexamplethatincludespointers,whichwillservetointroduceanewoperator: thearrowoperator(->):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

// pointers to structures #include <iostream> #include <string> #include <sstream> using namespace std; struct movies_t { string title; int year; }; int main () { string mystr;
movies_t amovie; movies_t * pmovie; pmovie = &amovie; cout << "Enter title: "; getline (cin, pmovie->title); cout << "Enter year: "; getline (cin, mystr); (stringstream) mystr >> pmovie->year; cout << "\nYou have entered:\n"; cout << pmovie->title; cout << " (" << pmovie->year << ")\n"; }

Enter title: Invasion of the body snatchers Enter year: 1978 You have entered: Invasion of the body snatchers (1978)

return 0;

Thepreviouscodeincludesanimportantintroduction:thearrowoperator(->).Thisisadereferenceoperator thatisusedexclusivelywithpointerstoobjectswithmembers.Thisoperatorservestoaccessamemberofan objecttowhichwehaveareference.Intheexampleweused:


pmovie->title

Whichisforallpurposesequivalentto:
(*pmovie).title

Bothexpressionspmovie->titleand(*pmovie).titlearevalidandbothmeanthatweare evaluatingthemembertitleofthedatastructurepointedbyapointercalledpmovie.Itmustbeclearly differentiatedfrom:

*pmovie.title

whichisequivalentto:
*(pmovie.title)

Andthatwouldaccessthevaluepointedbyahypotheticalpointermembercalledtitleofthestructure objectpmovie(whichinthiscasewouldnotbeapointer).Thefollowingpanelsummarizespossible combinationsofpointersandstructuremembers: Expression a.b a>b *a.b Whatisevaluated Memberbofobjecta Memberbofobjectpointedbya (*a).b Equivalent

Valuepointedbymemberbofobject *(a.b) a

Nestingstructures
Structurescanalsobenestedsothatavalidelementofastructurecanalsobeinitsturnanotherstructure. 1 2 3 4 5 6 7 8 9 10 11 12
struct movies_t { string title; int year; }; struct friends_t { string name; string email; movies_t favorite_movie; } charlie, maria;
friends_t * pfriends = &charlie;

Afterthepreviousdeclarationwecoulduseanyofthefollowingexpressions: 1 charlie.name
maria.favorite_movie.title

2 charlie.favorite_movie.year 3 pfriends->favorite_movie.year 4

(where,bytheway,thelasttwoexpressionsrefertothesamemember).

Exercise 1. Defineonestructurethatcontainmemberstructuresandcreateaninstanceorobjectof thattype a.displaythesizeofthestructureusingsizeofoperator(forthestructure definitionandobject) b.Getaddressoftheobjects 2. Create(define)astructurethatcontainmemberstructuresandmemberfunctions.Inthe mainprogramcreateaninstanceofthestructureandaccessthedatasusingmember functions 3. Whatisthedifferencebetweenclassandstructure?ShowthedifferencewithaC++ program. 4. Definetwostructures,S1&S2,thatcontainsmemberstructuresandmember functions.OnememberstructureofS2isinstanceofS1.Usinginstance(object)ofS2 trytoacces(use)memberfunction(s)ofS1.

TopOtherDataTypes
Defineddatatypes(typedef)
C++allowsthedefinitionofourowntypesbasedonotherexistingdatatypes.Wecandothisusingthe keywordtypedef,whoseformatis: typedef existing_type new_type_name ; whereexisting_typeisaC++fundamentalorcompoundtypeandnew_type_nameisthenamefor thenewtypewearedefining.Forexample: 1 typedef char C; 2 typedef unsigned int WORD; typedef char * pChar; 3

4 typedef char field [50];

Inthiscasewehavedefinedfourdatatypes:C,WORD,pCharandfieldaschar,unsigned int, char*andchar[50]respectively,thatwecouldperfectlyuseindeclarationslaterasanyothervalidtype: 1 2 3 4


C mychar, anotherchar, *ptc1; WORD myword; pChar ptc2; field name;

typedefdoesnotcreatedifferenttypes.Itonlycreatessynonymsofexistingtypes.Thatmeansthatthe typeofmywordcanbeconsideredtobeeitherWORDorunsigned int,sincebothareinfactthesame type. typedefcanbeusefultodefineanaliasforatypethatisfrequentlyusedwithinaprogram.Itisalsouseful todefinetypeswhenitispossiblethatwewillneedtochangethetypeinlaterversionsofourprogram,orif atypeyouwanttousehasanamethatistoolongorconfusing.

Unions
Unionsallowonesameportionofmemorytobeaccessedasdifferentdatatypes,sinceallofthemareinfact thesamelocationinmemory.Itsdeclarationanduseissimilartotheoneofstructuresbutitsfunctionalityis totallydifferent:
union union_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names;

Alltheelementsoftheuniondeclarationoccupythesamephysicalspaceinmemory.Itssizeistheoneof thegreatestelementofthedeclaration.Forexample: 1 union mytypes_t { 2 char c; int i; 3 float f; 4 } mytypes; 5

definesthreeelements:

1 mytypes.c 2 mytypes.i 3 mytypes.f

eachonewithadifferentdatatype.Sinceallofthemarereferringtothesamelocationinmemory,the modificationofoneoftheelementswillaffectthevalueofallofthem.Wecannotstoredifferentvaluesin themindependentofeachother. Oneoftheusesaunionmayhaveistouniteanelementarytypewithanarrayorstructuresofsmaller elements.Forexample: 1 union mix_t { 2 long l; 3 struct { 4 short hi; short lo; 5 } s; 6 char c[4]; 7 } mix; 8

definesthreenamesthatallowustoaccessthesamegroupof4bytes:mix.l,mix.sandmix.cand whichwecanuseaccordingtohowwewanttoaccessthesebytes,asiftheywereasinglelongtypedata, asiftheyweretwoshortelementsorasanarrayofcharelements,respectively.Ihavemixedtypes, arraysandstructuresintheunionsothatyoucanseethedifferentwaysthatwecanaccessthedata.Fora littleendiansystem(mostPCplatforms),thisunioncouldberepresentedas:

Theexactalignmentandorderofthemembersofaunioninmemoryisplatformdependant.Thereforebe awareofpossibleportabilityissueswiththistypeofuse.

Anonymousunions
InC++wehavetheoptiontodeclareanonymousunions.Ifwedeclareaunionwithoutanyname,theunion willbeanonymousandwewillbeabletoaccessitsmembersdirectlybytheirmembernames.Forexample, lookatthedifferencebetweenthesetwostructuredeclarations: structurewithregularunion structurewithanonymousunion
struct { char title[50]; char author[50]; union { float dollars; int yens; struct { char title[50]; char author[50]; union { float dollars; int yens;

} price; } book;

}; } book;

Theonlydifferencebetweenthetwopiecesofcodeisthatinthefirstonewehavegivenanametotheunion (price)andinthesecondonewehavenot.Thedifferenceisseenwhenweaccessthemembersdollars andyensofanobjectofthistype.Foranobjectofthefirsttype,itwouldbe: 1 book.price.dollars 2 book.price.yens

whereasforanobjectofthesecondtype,itwouldbe: 1 book.dollars 2 book.yens

OnceagainIremindyouthatbecauseitisaunionandnotastruct,themembersdollarsandyens occupythesamephysicalspaceinthememorysotheycannotbeusedtostoretwodifferentvalues simultaneously.Youcansetavalueforpriceindollarsorinyens,butnotinboth.

Enumerations(enum)
Enumerationscreatenewdatatypestocontainsomethingdifferentthatisnotlimitedtothevalues fundamentaldatatypesmaytake.Itsformisthefollowing:
enum enumeration_name { value1, value2, value3, . . } object_names;

Forexample,wecouldcreateanewtypeofvariablecalledcolors_ttostorecolorswiththefollowing declaration:
enum colors_t {black, blue, green, cyan, red, purple, yellow, white};

Noticethatwedonotincludeanyfundamentaldatatypeinthedeclaration.Tosayitsomehow,wehave createdawholenewdatatypefromscratchwithoutbasingitonanyotherexistingtype.Thepossiblevalues thatvariablesofthisnewtypecolor_tmaytakearethenewconstantvaluesincludedwithinbraces.For example,oncethecolors_tenumerationisdeclaredthefollowingexpressionswillbevalid:

1 colors_t mycolor; 2 3 mycolor = blue; 4 if (mycolor == green) mycolor = red;

Enumerationsaretypecompatiblewithnumericvariables,sotheirconstantsarealwaysassignedaninteger numericalvalueinternally.Ifitisnotspecified,theintegervalueequivalenttothefirstpossiblevalueis equivalentto0andthefollowingonesfollowa+1progression.Thus,inourdatatypecolors_tthatwe havedefinedabove,blackwouldbeequivalentto0,bluewouldbeequivalentto1,greento2,andso on. Wecanexplicitlyspecifyanintegervalueforanyoftheconstantvaluesthatourenumeratedtypecantake.If theconstantvaluethatfollowsitisnotgivenanintegervalue,itisautomaticallyassumedthesamevalueas thepreviousoneplusone.Forexample: 1 enum months_t { january=1, february, march, april, may, june, july, august, 2 september, october, november, december} y2k; 3

Inthiscase,variabley2kofenumeratedtypemonths_tcancontainanyofthe12possiblevaluesthatgo fromjanuarytodecemberandthatareequivalenttovaluesbetween1and12(notbetween0and11, sincewehavemadejanuaryequalto1).

You might also like