Académique Documents
Professionnel Documents
Culture Documents
8aNamingconflictsandthestdnamespace
BYALEXO NNO VEMBER6T H,2016| LAST MO DIF IEDBYALEXO NNO VEMBER9T H,2016
Letssayyouaredrivingtoafriendshouseforthefirsttime,andtheaddressgaventoyouis245FrontStreetinMillCity.Upon
reachingMillCity,youpullupyourmap,onlytodiscoverthatMillCityactuallyhastwodifferentFrontStreetsacrosstownfrom
eachother!Whichonewouldyougoto?Unlessthereweresomeadditionalcluetohelpyoudecide(e.g.yourememberhis
houseisnearaparticulardonutshop)youdhavetocallyourfriendandaskformoreinformation.Becausethiswouldbe
confusingandinefficient(particularlyforyourmailman),allstreetnames(andhousenumbers)inacityarerequiredtobeunique.
Similarly,C++requiresthatallidentifiers(variableand/orfunctionnames)benonambiguous.Iftwoidentifiersareintroduced
intothesameprograminawaythatthecompilercanttellthemapart,thecompilerorlinkerwillproduceanerror.Thiserroris
generallyreferredtoasanamingcollision(ornamingconflict).
Anexampleofanamingcollision
a.cpp:
1 #include <iostream>
2
3 void doSomething(int x)
4 {
5 std::cout << x;
6 }
b.cpp:
1 #include <iostream>
2
3 void doSomething(int x)
4 {
5 std::cout << x * 2;
6 }
main.cpp:
Filesa.cpp,b.cpp,andmain.cppwillallcompilejustfine,sinceindividuallytheresnoproblem.However,whena.cppandb.cpp
areputinthesameprojecttogether,anamingconflictwilloccur,sincethefunctiondoSomething()isdefinedinboth.Thiswill
causealinkererror.
Mostnamingcollisionsoccurintwocases:
1)Twofilesareaddedintothesameprojectthathaveanfunction(orglobalvariable)withthesamename(linkererror).
2)Acodefileincludesaheaderfilethatcontainsaidentifierthatconflictswithsomethingelse(compileerror).Welldiscuss
headerfilesinthenextlesson.
Asprogramsgetlargerandusemoreidentifiers,theoddsofanamingcollisionbeingintroducedincreasessignificantly.The
goodnewsisthatC++providesplentyofmechanismsforavoidingnamingcollisions(suchaslocalscope,whichkeeps
variablesinsidefunctionsfromconflictingwitheachother,andnamespaces,whichwellintroduceshortly),somostofthetime
youwontneedtoworryaboutthis.
Thestdnamespace
WhenC++wasoriginallydesigned,alloftheidentifiersintheC++standardlibrary(suchascinandcout)wereavailabletobe
useddirectly.However,thismeantthatanyidentifierinthestandardlibrarycouldpotentiallyconflictwithanameyoupickedfor
yourownidentifiers.Codethatwasworkingmightsuddenlyhaveanamingconflictwhenyou#includedanewfilefromthe
standardlibrary.Orworse,programsthatwouldcompileunderoneversionofC++mightnotcompileunderafutureversionof
C++,asnewfunctionalityintroducedintothestandardlibrarycouldconflict.SoC++movedallofthefunctionalityinthe
standardlibraryintoaspecialareacalledanamespace.
Muchlikeacityguaranteesthatallroadswithinthecityhaveuniquenames,anamespaceguaranteesthatidentifierswithinthe
namespaceareunique.Thispreventstheidentifiersinanamespacefromconflictingwithotheridentifiers.
Itturnsoutthatstd::coutsnameisntreallystd::cout.Itsactuallyjustcout,andstdisthenameofthenamespaceitlives
inside.AllofthefunctionalityintheC++standardlibraryisdefinedinsideanamespacenamedstd(shortforstandard).Inthis
way,wedonthavetoworryaboutthefunctionalityofthestandardlibraryhavinganamingconflictwithourownidentifiers.
Welltalkmoreaboutnamespacesinafuturelessonandalsoteachyouhowtocreateyourown.Fornow,theonlythingyou
reallyneedtoknowaboutnamespacesisthatwheneverweuseanidentifier(likestd::cout)thatispartofthestandardlibrary,
weneedtotellthecompilerthatthatidentifierlivesinsidethestdnamespace.
Rule:Whenyouuseanidentifierinanamespace,youalwayshavetoidentifythenamespacealongwiththeidentifier
Explicitnamespacequalifierstd::
Themoststraightforwardwaytotellthecompilerthatcoutlivesinthestdnamespaceisbyusingthestd::prefix.For
example:
Thisisthesafestwaytousecout,becausetheresnoambiguityaboutwherecoutlives(itsclearlyinthestdnamespace).
C++providesothershortcutsforindicatingwhatnamespaceanidentifierispartof(viausingstatements).Wecoverthosein
lesson4.3cUsingstatements.
1.9Headerfiles
Index
1.8Programswithmultiplefiles
Sharethis:
9commentsto1.8aNamingconflictsandthestdnamespace
Jim
February8,2016at11:03amReply
Alex,
Thestatementbelowisrealconfusingandmaybeevenmisleading.Arentthereothercontainersinthe
standardlibrarybesides(stdnamespace)?So,stdnamesspaceisjustone(ormaybepartofone)ofthesecontainersisntit?
"Everythinginthestandardlibrarylivesinsideaspecialcontainer(calledanamespace)thatisnamedstd(shortfor
standard)."
Alex
February9,2016at1:37pmReply
NotthatImawareof.Everythinginthestandardlibrarylivesinsidethestdnamespace.
Perhapstheresabetterwordtousethancontainer.Maybearea?
Jim
February20,2016at2:44pmReply
ThanksAlex,Butitsabithardformetogetmymindaroundexactlywhatnamespaces
are,couldyougiveusabetterdescription?
ThisiskindofdumbbutImsureothershavewonderedaboutthis.Ivegotanotherquestionaboutstd::cin>>
x.Iknowthisputtheuserinputvalueofxintomemory.Butcanyouputanythingelseonthatsamelineof
codebesidesacomment?
Thanks
Alex
February21,2016at11:17amReply
Itshardtodescribenamespacesrightnowbecausewehaventcoveredsomeofthe
languagethatIreallyneedtodescribethemaccurately.Awaytothinkofthemfornow:
Namespacesapplyaprefixtovariableandtypenames.Thisprefixfunctionsmuchlikeyourlastnamein
reallifedoesithelpsensurethateventhoughyoumayhavethesamefirstnameassomeoneelse,you
canstillbeuniquelyidentifiedbyusingbothyournamestogether.Doesthatmakesense?Italkmore
aboutnamespacesinchapter4.
Asforyoursecondquestion,becausethisstatementendsinasemicolon,youcouldputanotherstatement
totherightofthatstatement.However,thatsgenerallyconsideredbadform.Onestatementperlineisthe
recommendedpractice,withanoptionalcommenttotheright(orabove).
Big"B"LuvRRR
March15,2016at10:15amReply
Regardingnamingcollisionsornamingconflicts:couldntwejustcreatenamesthatarepracticallyguaranteed
nottoevercollideorconflicts,justaddinganextra"xy0"totheendofeveryfunctionwemake???
Surelytherecanbenoproblemwitha"coutxy0()"or"cinz()"oranythingsimilarlynamed!Iplanonusingaglobal
namespacedirectiveattheoutsetandnotworryingaboutcollisionsafterwardsbyjustcreatingveryuniquethoughsimple
functionnames.Whatcouldpossiblygowrongwithsuchanapproach,please?
Alex
March17,2016at2:28pmReply
Youcould,butdoingsomakesyourcodehardertoreadandrememberhowtouse(e.g.wasthe
functionnamedcoutxy0()orcoutx0()orcoutxy1()orwhat?).
GeorgesTheodosiou
November10,2016at3:09amReply
MydearTeacher,
pleaseletmesaythatIunderstand"Anexampleofanamingcollision"asfollows:
1 #include <iostream>
2
3 void doSomething(int x)
4 {
5 std::cout << x << std::endl;
6 std::cout << x * 2;
7 }
8 int main()
9 {
10 doSomething(5);
11
12 return 0;
13 }
Outputis:
5
10
Ibegyourcomments.
Withregardsandfriendship.
Alex
November10,2016at12:42pmReply
Thereisnonamingcollisionhere.Anamingcollisionhappenswhentwoidentifierscantbe
disambiguated.Thisprogramrunsfine.
GeorgesTheodosiou
November12,2016at6:30amReply
Mydearc++Teacher,
Pleaseacceptmymanythanksforyourreply.Ididnotputaandbfilesinsameproject,but
mergetheminsamefile.
Withregardsandfriendship.