C++ (OOP) Tutorial
C++ (OOP) Tutorial
C++ (OOP) Tutorial
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;
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
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; }
using namespace std; int main () { cout << "Hello World! "; cout << "I'm a C++ program";
9 10 return 0; } 11 12
Wewerealsofreetodividethecodeintomorelinesifweconsidereditmoreconvenient: 1 int main () 2 { 3 cout << 4 "Hello World!"; cout 5 << "I'm a C++ program"; 6 return 0; 7 } 8
Comments
Commentsarepartsofthesourcecodedisregardedbythecompiler.Theysimplydonothing.Theirpurpose isonlytoallowtheprogrammertoinsertnotesordescriptionsembeddedwithinthesourcecode. C++supportstwowaystoinsertcomments: 1 // line comment 2 /* block comment */
Thefirstofthem,knownaslinecomment,discardseverythingfromwherethepairofslashsigns(//)is founduptotheendofthatsameline.Thesecondone,knownasblockcomment,discardseverything
int main () { cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ program"; // prints I'm a C++ program return 0; }
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";
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.";
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;
StandardInput(cin).
Thestandardinputdeviceisusuallythekeyboard.HandlingthestandardinputinC++isdonebyapplying theoverloadedoperatorofextraction(>>)onthecinstream.Theoperatormustbefollowedbythevariable thatwillstorethedatathatisgoingtobeextractedfromthestream.Forexample: 1 int age; 2 cin >> age;
Thefirststatementdeclaresavariableoftypeintcalledage,andthesecondonewaitsforaninputfrom cin(thekeyboard)inordertostoreitinthisintegervariable.
// 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; }
Inbothcasestheusermustgivetwodata,oneforvariableaandanotheroneforvariablebthatmaybe separatedbyanyvalidblankseparator:aspace,atabcharacteroranewline.
cinandstrings
Wecanusecintogetstringswiththeextractionoperator(>>)aswedowithfundamentaldatatype variables:
cin >> mystring;
// 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;
// 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;
TopNamespaces
Namespacesallowtogroupentitieslikeclasses,objectsandfunctionsunderaname.Thiswaytheglobal scopecanbedividedin"subscopes",eachonewithitsownname. Theformatofnamespacesis: namespace identifier { entities } Whereidentifierisanyvalididentifierandentitiesisthesetofclasses,objectsandfunctionsthat areincludedwithinthenamespace.Forexample: 1 namespace myNamespace 2 { int a, b; 3 } 4
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
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
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
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
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
// 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.
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;
structureobjectsapple,bananaandmelonatthemomentwedefinethedatastructuretypethisway: 1 struct product { 2 int weight; float price; 3 } apple, banana, melon; 4
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"; }
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
Hereamovieisanobjectofstructuretypemovies_t,andpmovieisapointertopointtoobjectsof structuretypemovies_t.So,thefollowingcodewouldalsobevalid:
pmovie = &amovie;
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;
Whichisforallpurposesequivalentto:
(*pmovie).title
*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
Unions
Unionsallowonesameportionofmemorytobeaccessedasdifferentdatatypes,sinceallofthemareinfact thesamelocationinmemory.Itsdeclarationanduseissimilartotheoneofstructuresbutitsfunctionalityis totallydifferent:
union union_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names;
definesthreeelements:
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
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;
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};
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