You are on page 1of 16

C++

FromWikipedia,thefreeencyclopedia

C++(pronouncedasceeplusplus,/siplspls/)isa
generalpurposeprogramminglanguage.Ithas
imperative,objectorientedandgenericprogramming
features,whilealsoprovidingfacilitiesforlowlevel
memorymanipulation.

C++
Paradigm

Multiparadigm:procedural,
functional,objectoriented,
generic[1]

Itwasdesignedwithabiastowardsystemprogramming
andembedded,resourceconstrainedandlargesystems,
withperformance,efficiencyandflexibilityofuseasits
designhighlights.[3]C++hasalsobeenfoundusefulin
manyothercontexts,withkeystrengthsbeingsoftware
infrastructureandresourceconstrainedapplications,[3]
includingdesktopapplications,servers(e.g.ecommerce,
websearchorSQLservers),performancecritical
applications(e.g.telephoneswitchesorspaceprobes),
andentertainmentsoftware.[4]C++isacompiled
language,withimplementationsofitavailableonmany
platformsandprovidedbyvariousorganizations,
includingtheFSF,LLVM,Microsoft,IntelandIBM.

Designedby

C++isstandardizedbytheInternationalOrganizationfor
Standardization(ISO),withthelatest(andcurrent)
standardversionratifiedandpublishedbyISOin
December2014asISO/IEC14882:2014(informally
knownasC++14).[5]TheC++programminglanguage
wasinitiallystandardizedin1998asISO/IEC
14882:1998,whichwasthenamendedbytheC++03,
ISO/IEC14882:2003,standard.ThecurrentC++14
standardsupersedestheseandC++11,withnewfeatures
andanenlargedstandardlibrary.Beforetheinitial
standardizationin1998,C++wasdevelopedbyBjarne
StroustrupatBellLabssince1979,asanextensionofthe
Clanguageashewantedanefficientandflexible
languagesimilartoC,whichalsoprovidedhighlevel
featuresforprogramorganization.

BjarneStroustrup

Firstappeared 1983
Stablerelease

ISO/IEC14882:2014/
15December2014

Typing
discipline

Static,nominative,partially
inferred

Implementation C++
language
OS

Crossplatform(multiplatform)

Filename
extensions

.cc.cpp.cxx.C.c++.h.hh.hpp
.hxx.h++

Website

isocpp.org(http://isocpp.org/)
Majorimplementations

LLVMClang,GCC,MicrosoftVisualC++,
EmbarcaderoC++Builder,IntelC++Compiler,
IBMXLC++
Influencedby
C,Simula,ALGOL68,Ada,CLU,ML
Influenced
Perl,Lua,Ada95,Java,PHP,D,C99,C#[2]
C++ProgrammingatWikibooks

ManyotherprogramminglanguageshavebeeninfluencedbyC++,includingC#,Java,andnewerversions
ofC(after1998).

Contents
1History
1.1Etymology

1.1Etymology
1.2Philosophy
1.3Standardization
2Language
2.1Objectstorage
2.1.1Staticstoragedurationobjects
2.1.2Threadstoragedurationobjects
2.1.3Automaticstoragedurationobjects
2.1.4Dynamicstoragedurationobjects
2.2Templates
2.3Objects
2.3.1Encapsulation
2.3.2Inheritance
2.4Operatorsandoperatoroverloading
2.5Polymorphism
2.5.1Staticpolymorphism
2.5.2Dynamicpolymorphism
2.5.2.1Inheritance
2.5.2.2Virtualmemberfunctions
2.6Lambdaexpressions
2.7Exceptionhandling
3Standardlibrary
4Compatibility
4.1WithC
5Criticism
6Seealso
7References
8Furtherreading
9Externallinks

History
BjarneStroustrup,aDanishcomputerscientist,beganhisworkon
C++'spredecessor"CwithClasses"in1979.[6]Themotivationfor
creatinganewlanguageoriginatedfromStroustrup'sexperiencein
programmingforhisPh.D.thesis.StroustrupfoundthatSimulahad
featuresthatwereveryhelpfulforlargesoftwaredevelopment,but
thelanguagewastooslowforpracticaluse,whileBCPLwasfast
buttoolowleveltobesuitableforlargesoftwaredevelopment.
WhenStroustrupstartedworkinginAT&TBellLabs,hehadthe
problemofanalyzingtheUNIXkernelwithrespecttodistributed
computing.RememberinghisPh.D.experience,Stroustrupsetout
BjarneStroustrup,thecreatorofC++
toenhancetheClanguagewithSimulalikefeatures.[7]Cwas
chosenbecauseitwasgeneralpurpose,fast,portableandwidely
used.AswellasCandSimula'sinfluences,otherlanguagesalsoinfluencedC++,includingALGOL68,
Ada,CLUandML.

Initially,theclass,derivedclass,strongtyping,inlininganddefaultargumentfeatureswereaddedtoCvia
Stroustrup's"CwithClasses"toCcompiler,Cpre.[8]
In1983,itwasrenamedfromCwithClassestoC++("++"beingtheincrementoperatorinC).New
featureswereaddedincludingvirtualfunctions,functionnameandoperatoroverloading,references,
constants,typesafefreestorememoryallocation(new/delete),improvedtypechecking,andBCPLstyle
singlelinecommentswithtwoforwardslashes(//),aswellasthedevelopmentofapropercompilerfor
C++,Cfront.
In1985,thefirsteditionofTheC++ProgrammingLanguagewasreleased,whichbecamethedefinitive
referenceforthelanguage,astherewasnotyetanofficialstandard.[9]Thefirstcommercialimplementation
ofC++wasreleasedinOctoberofthesameyear.[6]
In1989,C++2.0wasreleased,followedbytheupdatedsecondeditionofTheC++Programming
Languagein1991.[10]Newfeaturesin2.0includedmultipleinheritance,abstractclasses,staticmember
functions,constmemberfunctions,andprotectedmembers.In1990,TheAnnotatedC++Reference
Manualwaspublished.Thisworkbecamethebasisforthefuturestandard.Laterfeatureadditionsincluded
templates,exceptions,namespaces,newcasts,andabooleantype.
Afterthe2.0update,C++evolvedrelativelyslowly.In2011,theC++11standardwasreleased,adding
numerousnewfeatures,enlargingthestandardlibraryfurther,andprovidingmorefacilitiestoC++
programmers.AfteraminorC++14update,releasedinDecember2014,variousnewadditionsareplanned
for2017.

Etymology
AccordingtoStroustrup:"thenamesignifiestheevolutionarynatureofthechangesfromC".[11]Thisname
iscreditedtoRickMascitti(mid1983)[8]andwasfirstusedinDecember1983.WhenMascittiwas
questionedinformallyin1992aboutthenaming,heindicatedthatitwasgiveninatongueincheekspirit.
ThenamestemsfromC's"++"operator(whichincrementsthevalueofavariable)andacommonnaming
conventionofusing"+"toindicateanenhancedcomputerprogram.
DuringC++'sdevelopmentperiod,thelanguagehadbeenreferredtoas"newC"and"CwithClasses"[8][12]
beforeacquiringitsfinalname.

Philosophy
ThroughoutC++'slife,itsdevelopmentandevolutionhasbeeninformallygovernedbyasetofrulesthatits
evolutionshouldfollow:[7]
Itmustbedrivenbyactualproblemsanditsfeaturesshouldbeusefulimmediatelyinrealworld
programs.
Everyfeatureshouldbeimplementable(withareasonablyobviouswaytodoso).
Programmersshouldbefreetopicktheirownprogrammingstyle,andthatstyleshouldbefully
supportedbyC++.
AllowingausefulfeatureismoreimportantthanpreventingeverypossiblemisuseofC++.
Itshouldprovidefacilitiesfororganisingprogramsintowelldefinedseparateparts,andprovide

facilitiesforcombiningseparatelydevelopedparts.
Noimplicitviolationsofthetypesystem(butallowexplicitviolationsthatis,thoseexplicitly
requestedbytheprogrammer).
Usercreatedtypesneedtohavethesamesupportandperformanceasbuiltintypes.
Unusedfeaturesshouldnotnegativelyimpactcreatedexecutables(e.g.inlowerperformance).
ThereshouldbenolanguagebeneathC++(exceptassemblylanguage).
C++shouldworkalongsideotherexistingprogramminglanguages,ratherthanfosteringitsown
separateandincompatibleprogrammingenvironment.
Iftheprogrammer'sintentisunknown,allowtheprogrammertospecifyitbyprovidingmanual
control.

Standardization
Year

C++Standard

Informalname

1998 ISO/IEC14882:1998[13]

C++98

2003 ISO/IEC14882:2003[14]

C++03

2007 ISO/IECTR19768:2007[15] C++07/TR1


2011 ISO/IEC14882:2011[5]

C++11

2014 ISO/IEC14882:2014[16]

C++14

2017 tobedetermined

C++17

C++isstandardizedbyanISOworkinggroupknownasJTC1/SC22/WG21.Sofar,ithasseenfive
versionsofC++releasedandiscurrentlyworkingonreleasingC++17.
In1998,theISOworkinggroupstandardizedC++forthefirsttimeasISO/IEC14882:1998,whichis
informallyknownasC++98.In2003,itpublishedanewversionoftheC++standardcalledISO/IEC
14882:2003,whichfixedproblemsidentifiedinC++98.
In2005,atechnicalreportwasreleased,calledthe"LibraryTechnicalReport1"(TR1).Whilenotan
officialpartofthestandard,itproposedanumberofextensionstothestandardlibrary.
Thenextmajorrevisionofthestandardwasinformallyreferredtoas"C++0x",butitwasnotreleaseduntil
2011.[17]C++11(14882:2011)includedmostofthelibraryenhancementsofTR1,aswellasmany
additionstothecorelanguage.[5]
In2014,C++14(alsoknownasC++1y)wasreleasedasasmallextensiontoC++11,featuringmainlybug
fixesandsmallimprovements.[18]TheDraftInternationalStandardballotprocedurescompletedinmid
August2014.[19]
AfterC++14,amajorrevision,informallyknownasC++17,isplannedfor2017.[18]
Aspartofthestandardizationprocess,theISOpublishesseveralkindsofpublications.Inparticular,
technicalreportsandtechnicalspecificationsarepublishedwhen"thereisthefuturebutnotimmediate
possibilityofanagreementtopublishanInternationalStandard."Until2011,threetechnicalreportson
C++werepublished:TR19768:2007(alsoknownastheC++TechnicalReport1)onlibraryextensions

mostlyintegratedintoC++11,TR29124:2010onspecialmathematicalfunctions,andTR24733:2011on
decimalfloatingpointarithmetic.ThetechnicalspecificationDTS18822:2014(onfilesystemoperations)
wasapprovedinearly2015,andmoretechnicalspecificationsareindevelopmentandpendingapproval.[20]

Language
TheC++languagehastwomaincomponents:adirectmappingofhardwarefeaturesprovidedprimarilyby
theCsubset,andzerooverheadabstractionsbasedonthosemappings.StroustrupdescribesC++as"a
lightweightabstractionprogramminglanguage[designed]forbuildingandusingefficientandelegant
abstractions"[3]and"offeringbothhardwareaccessandabstractionisthebasisofC++.Doingitefficiently
iswhatdistinguishesitfromotherlanguages".[21]
C++inheritsmostofC'ssyntax.ThefollowingisBjarneStroustrup'sversionoftheHelloworldprogram
thatusestheC++StandardLibrarystreamfacilitytowriteamessagetostandardoutput:[22][23]
#include<iostream>
intmain()
{
std::cout<<"Hello,world!\n";
}

Withinfunctionsthatdefineanonvoidreturntype,failuretoreturnavaluebeforecontrolreachestheend
ofthefunctionresultsinundefinedbehaviour(compilerstypicallyprovidethemeanstoissueadiagnostic
insuchacase).[24]Thesoleexceptiontothisruleisthemainfunction,whichimplicitlyreturnsavalueof
zero.[25]

Objectstorage
AsinC,C++supportsfourtypesofmemorymanagement:staticstoragedurationobjects,threadstorage
durationobjects,automaticstoragedurationobjects,anddynamicstoragedurationobjects.[26]
Staticstoragedurationobjects
Staticstoragedurationobjectsarecreatedbeforemain()isentered(seeexceptionsbelow)anddestroyedin
reverseorderofcreationaftermain()exits.Theexactorderofcreationisnotspecifiedbythestandard
(thoughtherearesomerulesdefinedbelow)toallowimplementationssomefreedominhowtoorganize
theirimplementation.Moreformally,objectsofthistypehavealifespanthat"shalllastforthedurationof
theprogram".[27]
Staticstoragedurationobjectsareinitializedintwophases.First,"staticinitialization"isperformed,and
onlyafterallstaticinitializationisperformed,"dynamicinitialization"isperformed.Instaticinitialization,
allobjectsarefirstinitializedwithzerosafterthat,allobjectsthathaveaconstantinitializationphaseare
initializedwiththeconstantexpression(i.e.variablesinitializedwithaliteralorconstexpr).Thoughitis
notspecifiedinthestandard,thestaticinitializationphasecanbecompletedatcompiletimeandsavedin
thedatapartitionoftheexecutable.Dynamicinitializationinvolvesallobjectinitializationdoneviaa

constructororfunctioncall(unlessthefunctionismarkedwithconstexpr,inC++11).Thedynamic
initializationorderisdefinedastheorderofdeclarationwithinthecompilationunit(i.e.thesamefile).No
guaranteesareprovidedabouttheorderofinitializationbetweencompilationunits.
Threadstoragedurationobjects
VariablesofthistypeareverysimilartoStaticStoragedurationobjects.Themaindifferenceisthecreation
timeisjustpriortothreadcreationanddestructionisdoneafterthethreadhasbeenjoined.[28]
Automaticstoragedurationobjects
ThemostcommonvariabletypesinC++arelocalvariablesinsideafunctionorblock,andtemporary
variables.[29]Thecommonfeatureaboutautomaticvariablesisthattheyhavealifetimethatislimitedtothe
scopeofthevariable.Theyarecreatedandpotentiallyinitializedatthepointofdeclaration(seebelowfor
details)anddestroyedinthereverseorderofcreationwhenthescopeisleft.
Localvariablesarecreatedasthepointofexecutionpassesthedeclarationpoint.Ifthevariablehasa
constructororinitializerthisisusedtodefinetheinitialstateoftheobject.Localvariablesaredestroyed
whenthelocalblockorfunctionthattheyaredeclaredinisclosed.C++destructorsforlocalvariablesare
calledattheendoftheobjectlifetime,allowingadisciplineforautomaticresourcemanagementtermed
RAII,whichiswidelyusedinC++.
Membervariablesarecreatedwhentheparentobjectiscreated.Arraymembersareinitializedfrom0tothe
lastmemberofthearrayinorder.Membervariablesaredestroyedwhentheparentobjectisdestroyedin
thereverseorderofcreation.i.e.Iftheparentisan"automaticobject"thenitwillbedestroyedwhenitgoes
outofscopewhichtriggersthedestructionofallitsmembers.
Temporaryvariablesarecreatedastheresultofexpressionevaluationandaredestroyedwhenthestatement
containingtheexpressionhasbeenfullyevaluated(usuallyatthe;attheendofastatement).
Dynamicstoragedurationobjects
Theseobjectshaveadynamiclifespanandarecreatedwithnewcallanddestroyedwithanexplicitcallto
delete.[30]

Templates
Seealso:TemplatemetaprogrammingandGenericprogramming
C++templatesenablegenericprogramming.C++supportsbothfunctionandclasstemplates.Templates
maybeparameterizedbytypes,compiletimeconstants,andothertemplates.Templatesareimplemented
byinstantiationatcompiletime.Toinstantiateatemplate,compilerssubstitutespecificargumentsfora
template'sparameterstogenerateaconcretefunctionorclassinstance.Somesubstitutionsarenotpossible
theseareeliminatedbyanoverloadresolutionpolicydescribedbythephrase"Substitutionfailureisnotan
error"(SFINAE).Templatesareapowerfultoolthatcanbeusedforgenericprogramming,template
metaprogramming,andcodeoptimization,butthispowerimpliesacost.Templateusemayincreasecode
size,becauseeachtemplateinstantiationproducesacopyofthetemplatecode:oneforeachsetoftemplate

arguments,however,thisisthesameorsmalleramountofcodethatwouldbegeneratedifthecodewas
writtenbyhand.[31]Thisisincontrasttoruntimegenericsseeninotherlanguages(e.g.,Java)whereat
compiletimethetypeiserasedandasingletemplatebodyispreserved.
Templatesaredifferentfrommacros:whilebothofthesecompiletimelanguagefeaturesenableconditional
compilation,templatesarenotrestrictedtolexicalsubstitution.Templatesareawareofthesemanticsand
typesystemoftheircompanionlanguage,aswellasallcompiletimetypedefinitions,andcanperform
highleveloperationsincludingprogrammaticflowcontrolbasedonevaluationofstrictlytypechecked
parameters.Macrosarecapableofconditionalcontrolovercompilationbasedonpredeterminedcriteria,but
cannotinstantiatenewtypes,recurse,orperformtypeevaluationandineffectarelimitedtopre
compilationtextsubstitutionandtextinclusion/exclusion.Inotherwords,macroscancontrolcompilation
flowbasedonpredefinedsymbolsbutcannot,unliketemplates,independentlyinstantiatenewsymbols.
Templatesareatoolforstaticpolymorphism(seebelow)andgenericprogramming.
Inaddition,templatesareacompiletimemechanisminC++thatisTuringcomplete,meaningthatany
computationexpressiblebyacomputerprogramcanbecomputed,insomeform,byatemplate
metaprogrampriortoruntime.
Insummary,atemplateisacompiletimeparameterizedfunctionorclasswrittenwithoutknowledgeofthe
specificargumentsusedtoinstantiateit.Afterinstantiation,theresultingcodeisequivalenttocodewritten
specificallyforthepassedarguments.Inthismanner,templatesprovideawaytodecouplegeneric,broadly
applicableaspectsoffunctionsandclasses(encodedintemplates)fromspecificaspects(encodedin
templateparameters)withoutsacrificingperformanceduetoabstraction.

Objects
Mainarticle:C++classes
C++introducesobjectorientedprogramming(OOP)featurestoC.Itoffersclasses,whichprovidethefour
featurescommonlypresentinOOP(andsomenonOOP)languages:abstraction,encapsulation,inheritance,
andpolymorphism.OnedistinguishingfeatureofC++classescomparedtoclassesinotherprogramming
languagesissupportfordeterministicdestructors,whichinturnprovidesupportfortheResource
AcquisitionisInitialization(RAII)concept.
Encapsulation
Encapsulationisthehidingofinformationtoensurethatdatastructuresandoperatorsareusedasintended
andtomaketheusagemodelmoreobvioustothedeveloper.C++providestheabilitytodefineclassesand
functionsasitsprimaryencapsulationmechanisms.Withinaclass,memberscanbedeclaredaseither
public,protected,orprivatetoexplicitlyenforceencapsulation.Apublicmemberoftheclassisaccessible
toanyfunction.Aprivatememberisaccessibleonlytofunctionsthataremembersofthatclassandto
functionsandclassesexplicitlygrantedaccesspermissionbytheclass("friends").Aprotectedmemberis
accessibletomembersofclassesthatinheritfromtheclassinadditiontotheclassitselfandanyfriends.
TheOOprincipleisthatallofthefunctions(andonlythefunctions)thataccesstheinternalrepresentation
ofatypeshouldbeencapsulatedwithinthetypedefinition.C++supportsthis(viamemberfunctionsand
friendfunctions),butdoesnotenforceit:theprogrammercandeclarepartsoralloftherepresentationofa

typetobepublic,andisallowedtomakepublicentitiesthatarenotpartoftherepresentationofthetype.
Therefore,C++supportsnotjustOOprogramming,butotherweakerdecompositionparadigms,like
modularprogramming.
Itisgenerallyconsideredgoodpracticetomakealldataprivateorprotected,andtomakepubliconlythose
functionsthatarepartofaminimalinterfaceforusersoftheclass.Thiscanhidethedetailsofdata
implementation,allowingthedesignertolaterfundamentallychangetheimplementationwithoutchanging
theinterfaceinanyway.[32][33]
Inheritance
Inheritanceallowsonedatatypetoacquirepropertiesofotherdatatypes.Inheritancefromabaseclassmay
bedeclaredaspublic,protected,orprivate.Thisaccessspecifierdetermineswhetherunrelatedandderived
classescanaccesstheinheritedpublicandprotectedmembersofthebaseclass.Onlypublicinheritance
correspondstowhatisusuallymeantby"inheritance".Theothertwoformsaremuchlessfrequentlyused.
Iftheaccessspecifierisomitted,a"class"inheritsprivately,whilea"struct"inheritspublicly.Baseclasses
maybedeclaredasvirtualthisiscalledvirtualinheritance.Virtualinheritanceensuresthatonlyone
instanceofabaseclassexistsintheinheritancegraph,avoidingsomeoftheambiguityproblemsof
multipleinheritance.
MultipleinheritanceisaC++featurenotfoundinmostotherlanguages,allowingaclasstobederivedfrom
morethanonebaseclassthisallowsformoreelaborateinheritancerelationships.Forexample,a"Flying
Cat"classcaninheritfromboth"Cat"and"FlyingMammal".Someotherlanguages,suchasC#orJava,
accomplishsomethingsimilar(althoughmorelimited)byallowinginheritanceofmultipleinterfaceswhile
restrictingthenumberofbaseclassestoone(interfaces,unlikeclasses,provideonlydeclarationsof
memberfunctions,noimplementationormemberdata).AninterfaceasinC#andJavacanbedefinedin
C++asaclasscontainingonlypurevirtualfunctions,oftenknownasanabstractbaseclassor"ABC".The
memberfunctionsofsuchanabstractbaseclassarenormallyexplicitlydefinedinthederivedclass,not
inheritedimplicitly.C++virtualinheritanceexhibitsanambiguityresolutionfeaturecalleddominance.

Operatorsandoperatoroverloading
C++providesmorethan35operators,covering
basicarithmetic,bitmanipulation,indirection,
comparisons,logicaloperationsandothers.
Almostalloperatorscanbeoverloadedforuser
definedtypes,withafewnotableexceptions
suchasmemberaccess(.and.*)aswellasthe
conditionaloperator.Therichsetofoverloadable
operatorsiscentraltomakinguserdefinedtypes
inC++seemlikebuiltintypes.

Operatorsthatcannotbeoverloaded
Operator
Symbol
Scoperesolutionoperator ::
Conditionaloperator

?:

dotoperator

Memberselectionoperator .*
"sizeof"operator

sizeof

"typeid"operator
typeid
Overloadableoperatorsarealsoanessentialpart
ofmanyadvancedC++programming
techniques,suchassmartpointers.Overloadinganoperatordoesnotchangetheprecedenceofcalculations
involvingtheoperator,nordoesitchangethenumberofoperandsthattheoperatoruses(anyoperandmay
howeverbeignoredbytheoperator,thoughitwillbeevaluatedpriortoexecution).Overloaded"&&"and
"||"operatorslosetheirshortcircuitevaluationproperty.

Polymorphism
Seealso:Polymorphisminobjectorientedprogramming
Polymorphismenablesonecommoninterfaceformanyimplementations,andforobjectstoactdifferently
underdifferentcircumstances.
C++supportsseveralkindsofstatic(compiletime)anddynamic(runtime)polymorphisms,supportedby
thelanguagefeaturesdescribedabove.Compiletimepolymorphismdoesnotallowforcertainruntime
decisions,whileruntimepolymorphismtypicallyincursaperformancepenalty.
Staticpolymorphism
Seealso:Parametricpolymorphismandadhocpolymorphism
Functionoverloadingallowsprogramstodeclaremultiplefunctionshavingthesamenamebutwith
differentarguments(i.e.adhocpolymorphism).Thefunctionsaredistinguishedbythenumberortypesof
theirformalparameters.Thus,thesamefunctionnamecanrefertodifferentfunctionsdependingonthe
contextinwhichitisused.Thetypereturnedbythefunctionisnotusedtodistinguishoverloadedfunctions
andwouldresultinacompiletimeerrormessage.
Whendeclaringafunction,aprogrammercanspecifyforoneormoreparametersadefaultvalue.Doingso
allowstheparameterswithdefaultstooptionallybeomittedwhenthefunctioniscalled,inwhichcasethe
defaultargumentswillbeused.Whenafunctioniscalledwithfewerargumentsthantherearedeclared
parameters,explicitargumentsarematchedtoparametersinlefttorightorder,withanyunmatched
parametersattheendoftheparameterlistbeingassignedtheirdefaultarguments.Inmanycases,
specifyingdefaultargumentsinasinglefunctiondeclarationispreferabletoprovidingoverloadedfunction
definitionswithdifferentnumbersofparameters.
TemplatesinC++provideasophisticatedmechanismforwritinggeneric,polymorphiccode(i.e.
parametricpolymorphism).Inparticular,throughtheCuriouslyRecurringTemplatePattern,it'spossibleto
implementaformofstaticpolymorphismthatcloselymimicsthesyntaxforoverridingvirtualfunctions.
BecauseC++templatesaretypeawareandTuringcomplete,theycanalsobeusedtoletthecompiler
resolverecursiveconditionalsandgeneratesubstantialprogramsthroughtemplatemetaprogramming.
Contrarytosomeopinion,templatecodewillnotgenerateabulkcodeaftercompilationwiththeproper
compilersettings.[31]
Dynamicpolymorphism
Inheritance

Seealso:Subtyping
Variablepointers(andreferences)toabaseclasstypeinC++canrefertoobjectsofanyderivedclassesof
thattypeinadditiontoobjectsexactlymatchingthevariabletype.Thisallowsarraysandotherkindsof
containerstoholdpointerstoobjectsofdifferingtypes.Becauseassignmentofvaluestovariablesusually
occursatruntime,thisisnecessarilyaruntimephenomenon.

C++alsoprovidesadynamic_castoperator,whichallowstheprogramtosafelyattemptconversionofan
objectintoanobjectofamorespecificobjecttype(asopposedtoconversiontoamoregeneraltype,which
isalwaysallowed).Thisfeaturereliesonruntimetypeinformation(RTTI).Objectsknowntobeofa
certainspecifictypecanalsobecasttothattypewithstatic_cast,apurelycompiletimeconstructthathas
noruntimeoverheadanddoesnotrequireRTTI.
Virtualmemberfunctions

Ordinarily,whenafunctioninaderivedclassoverridesafunctioninabaseclass,thefunctiontocallis
determinedbythetypeoftheobject.Agivenfunctionisoverriddenwhenthereexistsnodifferenceinthe
numberortypeofparametersbetweentwoormoredefinitionsofthatfunction.Hence,atcompiletime,it
maynotbepossibletodeterminethetypeoftheobjectandthereforethecorrectfunctiontocall,givenonly
abaseclasspointerthedecisionisthereforeputoffuntilruntime.Thisiscalleddynamicdispatch.Virtual
memberfunctionsormethods[34]allowthemostspecificimplementationofthefunctiontobecalled,
accordingtotheactualruntimetypeoftheobject.InC++implementations,thisiscommonlydoneusing
virtualfunctiontables.Iftheobjecttypeisknown,thismaybebypassedbyprependingafullyqualified
classnamebeforethefunctioncall,butingeneralcallstovirtualfunctionsareresolvedatruntime.
Inadditiontostandardmemberfunctions,operatoroverloadsanddestructorscanbevirtual.Asaruleof
thumb,ifanyfunctionintheclassisvirtual,thedestructorshouldbeaswell.Asthetypeofanobjectatits
creationisknownatcompiletime,constructors,andbyextensioncopyconstructors,cannotbevirtual.
Nonethelessasituationmayarisewhereacopyofanobjectneedstobecreatedwhenapointertoaderived
objectispassedasapointertoabaseobject.Insuchacase,acommonsolutionistocreateaclone()(or
similar)virtualfunctionthatcreatesandreturnsacopyofthederivedclasswhencalled.
Amemberfunctioncanalsobemade"purevirtual"byappendingitwith=0aftertheclosingparenthesis
andbeforethesemicolon.Aclasscontainingapurevirtualfunctioniscalledanabstractdatatype.Objects
cannotbecreatedfromabstractdatatypestheycanonlybederivedfrom.Anyderivedclassinheritsthe
virtualfunctionaspureandmustprovideanonpuredefinitionofit(andallotherpurevirtualfunctions)
beforeobjectsofthederivedclasscanbecreated.Aprogramthatattemptstocreateanobjectofaclass
withapurevirtualmemberfunctionorinheritedpurevirtualmemberfunctionisillformed.

Lambdaexpressions
C++providessupportforanonymousfunctions,whicharealsoknownaslambdaexpressions.Alambda
expressionhasthefollowingform:
[capture](parameters)>return_type{function_body}

The[capture]listsupportsthedefinitionofclosures.Suchlambdaexpressionsaredefinedinthestandard
assyntacticsugarforanunnamedfunctionobject.Anexamplelambdafunctionmaybedefinedasfollows:
[](intx,inty)>int{returnx+y;}

Exceptionhandling

Exceptionhandlingisusedtocommunicatetheexistenceofaruntimeproblemorerrorfromwhereitwas
detectedtowheretheissuecanbehandled.[35]Itpermitsthistobedoneinauniformmannerandseparately
fromthemaincode,whiledetectingallerrors.[36]Shouldanerroroccur,anexceptionisthrown(raised),
whichisthencaughtbythenearestsuitableexceptionhandler.Theexceptioncausesthecurrentscopetobe
exited,andalsoeachouterscope(propagation)untilasuitablehandlerisfound,callinginturnthe
destructorsofanyobjectsintheseexitedscopes.[37]Atthesametime,anexceptionispresentedasanobject
carryingthedataaboutthedetectedproblem.[38]
Theexceptioncausingcodeisplacedinsideatryblock.Theexceptionsarehandledinseparatecatch
blocks(thehandlers)eachtryblockcanhavemultipleexceptionhandlers,asitisvisibleintheexample
below.[39]
#include<iostream>
#include<vector>
intmain(){
try{
std::vector<int>vec{3,4,3,1};
inti{vec.at(4)};//Throwsanexception,std::out_of_range(indexingforvecisfrom03not14)
}
//Anexceptionhandler,catchesstd::out_of_range,whichisthrownbyvec.at(4)
catch(std::out_of_range&e){
std::cerr<<"Accessinganonexistentelement:"<<e.what()<<'\n';
}
//Tocatchanyotherstandardlibraryexceptions(theyderivefromstd::exception)
catch(std::exception&e){
std::cerr<<"Exceptionthrown:"<<e.what()<<'\n';
}
//Catchanyunrecognisedexceptions(i.e.thosewhichdon'tderivefromstd::exception)
catch(...){
std::cerr<<"Somefatalerror\n";
}
}

Itisalsopossibletoraiseexceptionspurposefully,usingthethrowkeywordtheseexceptionsarehandledin
theusualway.Insomecases,exceptionscannotbeusedduetotechnicalreasons.Onesuchexampleisa
criticalcomponentofanembeddedsystem,whereeveryoperationmustbeguaranteedtocompletewithina
specifiedamountoftime.Thiscannotbedeterminedwithexceptionsasnotoolsexisttodeterminethe
minimumtimerequiredforanexceptiontobehandled.[40]

Standardlibrary
TheC++standardconsistsoftwoparts:thecorelanguageandtheC++StandardLibrary.C++
programmersexpectthelatteroneverymajorimplementationofC++itincludesvectors,lists,maps,
algorithms(find,for_each,binary_search,random_shuffle,etc.),sets,queues,stacks,arrays,tuples,
input/outputfacilities(iostream,forreadingfromandwritingtotheconsoleandfiles),smartpointersfor
automaticmemorymanagement,regularexpressionsupport,multithreadinglibrary,atomicssupport
(allowingavariabletobereadorwrittentobeatmostonethreadatatimewithoutanyexternal

synchronisation),timeutilities(measurement,gettingcurrenttime,etc.),asystemforconvertingerror
reportingthatdoesn'tuseC++exceptionsintoC++exceptions,arandomnumbergeneratorandaslightly
modifiedversionoftheCstandardlibrary(tomakeitcomplywiththeC++typesystem).
AlargepartoftheC++libraryisbasedontheStandardTemplateLibrary(STL).Usefultoolsprovidedby
theSTLincludecontainersasthecollectionsofobjects(suchasvectorsandlists),iteratorsthatprovide
arraylikeaccesstocontainers,andalgorithmsthatperformoperationssuchassearchingandsorting.
Furthermore,(multi)maps(associativearrays)and(multi)setsareprovided,allofwhichexportcompatible
interfaces.Therefore,usingtemplatesitispossibletowritegenericalgorithmsthatworkwithanycontainer
oronanysequencedefinedbyiterators.AsinC,thefeaturesofthelibraryareaccessedbyusingthe
#includedirectivetoincludeastandardheader.C++provides105standardheaders,ofwhich27are
deprecated.
ThestandardincorporatestheSTLthatwasoriginallydesignedbyAlexanderStepanov,whoexperimented
withgenericalgorithmsandcontainersformanyyears.WhenhestartedwithC++,hefinallyfounda
languagewhereitwaspossibletocreategenericalgorithms(e.g.,STLsort)thatperformevenbetterthan,
forexample,theCstandardlibraryqsort,thankstoC++featureslikeusinginliningandcompiletime
bindinginsteadoffunctionpointers.Thestandarddoesnotrefertoitas"STL",asitismerelyapartofthe
standardlibrary,butthetermisstillwidelyusedtodistinguishitfromtherestofthestandardlibrary
(input/outputstreams,internationalization,diagnostics,theClibrarysubset,etc.).
MostC++compilers,andallmajorones,provideastandardsconformingimplementationoftheC++
standardlibrary.

Compatibility
Togivecompilervendorsgreaterfreedom,theC++standardscommitteedecidednottodictatethe
implementationofnamemangling,exceptionhandling,andotherimplementationspecificfeatures.The
downsideofthisdecisionisthatobjectcodeproducedbydifferentcompilersisexpectedtobe
incompatible.Therewere,however,attemptstostandardizecompilersforparticularmachinesoroperating
systems(forexampleC++ABI),[41]thoughtheyseemtobelargelyabandonednow.

WithC
Formoredetailsonthistopic,seeCompatibilityofCandC++.
C++isoftenconsideredtobeasupersetofC,butthisisnotstrictlytrue.[42]MostCcodecaneasilybe
madetocompilecorrectlyinC++,butthereareafewdifferencesthatcausesomevalidCcodetobeinvalid
orbehavedifferentlyinC++.Forexample,Callowsimplicitconversionfromvoid*tootherpointertypes,
butC++doesnot(fortypesafetyreasons).Also,C++definesmanynewkeywords,suchasnewandclass,
whichmaybeusedasidentifiers(forexample,variablenames)inaCprogram.
Someincompatibilitieshavebeenremovedbythe1999revisionoftheCstandard(C99),whichnow
supportsC++featuressuchaslinecomments(//),anddeclarationsmixedwithcode.Ontheotherhand,
C99introducedanumberofnewfeaturesthatC++didnotsupport,wereincompatibleorredundantinC++,
suchasvariablelengtharrays,nativecomplexnumbertypes(however,thestd::complexclassintheC++

standardlibraryiscloselycompatible),designatedinitializers,compoundliterals,andtherestrict
keyword.[43]SomeoftheC99introducedfeatureswereincludedinthesubsequentversionoftheC++
standard,C++11(outofthosewhichwerenotredundant).[44][45][46]
TointermixCandC++code,anyfunctiondeclarationordefinitionthatistobecalledfrom/usedbothinC
andC++mustbedeclaredwithClinkagebyplacingitwithinanextern"C"{/*...*/}block.Sucha
functionmaynotrelyonfeaturesdependingonnamemangling(i.e.,functionoverloading).

Criticism
Despiteitswidespreadadoption,manyprogrammershavecriticizedtheC++language,includingLinus
Torvalds,[47]RichardStallman,[48]andKenThompson.[49]SomeaspectsofC++thatareoftencriticizedare
itsexceptionhandling,slowcompilationtimes,andunnecessarycomplexity.[50]

Seealso
BjarneStroustrup
C++StandardLibrary
Comparisonofprogramminglanguages
InternationalOrganizationforStandardization
ListofC++compilers
OutlineofC++
TheC++ProgrammingLanguage

References
1. Stroustrup,Bjarne(1997)."1".TheC++ProgrammingLanguage(Thirded.).ISBN0201889544.
OCLC59193992.
2. Naugler,David(May2007)."C#2.0forC++andJavaprogrammer:conferenceworkshop".Journalof
ComputingSciencesinColleges22(5)."AlthoughC#hasbeenstronglyinfluencedbyJavaithasalsobeen
stronglyinfluencedbyC++andisbestviewedasadescendantofbothC++andJava."
3. Stroustrup,B.(6May2014)."Lecture:TheessenceofC++.UniversityofEdinburgh.".Retrieved12June2015.
4. Stroustrup,Bjarne(17February2014)."C++Applications".stroustrup.com.Retrieved5May2014.
5. "ISO/IEC14882:2011".InternationalOrganizationforStandardization.
6. Stroustrup,Bjarne(7March2010)."BjarneStroustrup'sFAQ:WhenwasC++invented?".stroustrup.com.
Retrieved16September2010.
7. Stroustrup,Bjarne."Evolvingalanguageinandfortherealworld:C++19912006"(PDF).
8. Stroustrup,Bjarne."AHistoryofC++:19791991"(PDF).
9. Stroustrup,Bjarne."TheC++ProgrammingLanguage"(Firsted.).Retrieved16September2010.
10. Stroustrup,Bjarne."TheC++ProgrammingLanguage"(Seconded.).Retrieved16September2010.
11. "BjarneStroustrup'sFAQWheredidthename"C++"comefrom?".Retrieved16January2008.
12. "CForC++Programmers".NortheasternUniversity.Retrieved7September2015.
13. "ISO/IEC14882:1998".InternationalOrganizationforStandardization.
14. "ISO/IEC14882:2003".InternationalOrganizationforStandardization.
15. "ISO/IECTR19768:2007".InternationalOrganizationforStandardization.
16. "ISO/IEC14882:2014".InternationalOrganizationforStandardization.
17. "Wehaveaninternationalstandard:C++0xisunanimouslyapproved".Sutter'sMill.
18. "TheFutureofC++".

19. "WehaveC++14!:StandardC++".
20. Seealistathttp://en.cppreference.com/w/cpp/experimentalVisited5January2015.
21. B.Stroustrup(interviewedbySergioDeSimone)(30April2015)."Stroustrup:ThoughtsonC++17An
Interview".Retrieved8July2015.
22. Stroustrup,Bjarne(2000).TheC++ProgrammingLanguage(Specialed.).AddisonWesley.p.46.ISBN0
201700735.
23. Stroustrup,Bjarne."OpenissuesforTheC++ProgrammingLanguage(3rdEdition)".Thiscodeiscopied
directlyfromBjarneStroustrup'serratapage(p.633).Headdressestheuseof'\n'ratherthanstd::endl.Also
seeCanIwrite"voidmain()"?foranexplanationoftheimplicitreturn0;inthemainfunction.Thisimplicit
returnisnotavailableinotherfunctions.
24. ISO/IEC(2003).ISO/IEC14882:2003(E):ProgrammingLanguagesC++6.6.3Thereturnstatement
[stmt.return]para.2
25. ISO/IEC(2003).ISO/IEC14882:2003(E):ProgrammingLanguagesC++3.6.1Mainfunction
[basic.start.main]para.5
26. ISO/IEC.ProgrammingLanguagesC++11Draft(n3797)(http://www.open
std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf)3.7Storageduration[basic.stc]
27. ISO/IEC.ProgrammingLanguagesC++11Draft(n3797)(http://www.open
std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf)3.7.1StaticStorageduration[basic.stc.static]
28. ISO/IEC.ProgrammingLanguagesC++11Draft(n3797)(http://www.open
std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf)3.7.2ThreadStorageduration[basic.stc.thread]
29. ISO/IEC.ProgrammingLanguagesC++11Draft(n3797)(http://www.open
std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf)3.7.3AutomaticStorageduration[basic.stc.auto]
30. ISO/IEC.ProgrammingLanguagesC++11Draft(n3797)(http://www.open
std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf)3.7.4DynamicStoragedurationbasic.stc.dynamic
31. "NobodyUnderstandsC++:Part5:TemplateCodeBloat".http://blog.emptycrate.com/:EmptyCrateSoftware.
Travel.Stuff.6May2008.Retrieved8March2010."Onoccasionyouwillreadorhearsomeonetalkingabout
C++templatescausingcodebloat.Iwasthinkingaboutittheotherdayandthoughttomyself,"self,ifthecode
doesexactlythesamethingthenthecompiledcodecannotreallybeanybigger,canit?"[...]Andwhatabout
compiledcodesize?Eachwerecompiledwiththecommandg++<filename>.cppO3.Nontemplateversion:
8140bytes,templateversion:8028bytes!"
32. Sutter,HerbAlexandrescu,Andrei(2004).C++CodingStandards:101Rules,Guidelines,andBestPractices.
AddisonWesley.
33. Henricson,MatsNyquist,Erik(1997).IndustrialStrengthC++.PrenticeHall.ISBN0131209655.
34. Stroustrup,Bjarne(2000).TheC++ProgrammingLanguage(Specialed.).AddisonWesley.p.310.ISBN0
201700735."Avirtualmemberfunctionissometimescalledamethod."
35. Mycroft,Alan(2013)."CandC++Exceptions|Templates"(PDF).CambridgeComputerLaboratoryCourse
Materials201314.RetrievedJuly2014.
36. Stroustrup,Bjarne(2013).TheC++ProgrammingLanguage.AddisonWesley.p.345.ISBN9780321563842.
37. Stroustrup,Bjarne(2013).TheC++ProgrammingLanguage.AddisonWesley.pp.363365.
ISBN9780321563842.
38. Stroustrup,Bjarne(2013).TheC++ProgrammingLanguage.AddisonWesley.pp.345,363.
ISBN9780321563842.
39. Stroustrup,Bjarne(2013).TheC++ProgrammingLanguage.AddisonWesley.pp.344,370.
ISBN9780321563842.
40. Stroustrup,Bjarne(2013).TheC++ProgrammingLanguage.AddisonWesley.p.349.ISBN9780321563842.
41. "C++ABISummary".20March2001.Retrieved30May2006.
42. "BjarneStroustrup'sFAQIsCasubsetofC++?".Retrieved5May2014.
43. "C9XTheNewCStandard".Retrieved27December2008.
44. "C++0xSupportinGCC".Retrieved12October2010.
45. "C++0xCoreLanguageFeaturesInVC10:TheTable".Retrieved12October2010.
46. "ClangC++98,C++11,andC++14Status".Clang.llvm.org.12May2013.Retrieved10June2013.
47. "Re:[RFC]Convertbuilinmailinfo.ctouseTheBetterStringLibrary"(Mailinglist).6September2007.
Retrieved31March2015.

48. "Re:Effortstoattractmoreusers?"(Mailinglist).12July2010.Retrieved31March2015.
49. AndrewBinstock(18May2011)."Dr.Dobb's:InterviewwithKenThompson".Retrieved7February2014.
50. "WhyshouldI[sic]havewrittenZeroMQinC,notC++".

Furtherreading
Abrahams,DavidGurtovoy,Aleksey.C++TemplateMetaprogramming:Concepts,Tools,andTechniquesfrom
BoostandBeyond.AddisonWesley.ISBN0321227255.
Alexandrescu,Andrei(2001).ModernC++Design:GenericProgrammingandDesignPatternsApplied.
AddisonWesley.ISBN0201704315.
Alexandrescu,AndreiSutter,Herb(2004).C++DesignandCodingStandards:RulesandGuidelinesfor
WritingPrograms.AddisonWesley.ISBN0321113586.
Becker,Pete(2006).TheC++StandardLibraryExtensions:ATutorialandReference.AddisonWesley.
ISBN0321412990.
Brokken,Frank(2010).C++Annotations.UniversityofGroningen.ISBN9036704707.
Coplien,JamesO.(1994)[reprintedwithcorrections,originalyearofpublication1992].AdvancedC++:
ProgrammingStylesandIdioms.ISBN0201548550.
Dewhurst,StephenC.(2005).C++CommonKnowledge:EssentialIntermediateProgramming.Addison
Wesley.ISBN0321321928.
InformationTechnologyIndustryCouncil(15October2003).ProgramminglanguagesC++(Seconded.).
Geneva:ISO/IEC.14882:2003(E).
Josuttis,NicolaiM.(2012).TheC++StandardLibrary,ATutorialandReference(Seconded.).Addison
Wesley.ISBN0321623215.
Koenig,AndrewMoo,BarbaraE.(2000).AcceleratedC++PracticalProgrammingbyExample.Addison
Wesley.ISBN020170353X.
Lippman,StanleyB.Lajoie,JoseMoo,BarbaraE.(2011).C++Primer(Fifthed.).AddisonWesley.
ISBN0470932449.
Lippman,StanleyB.(1996).InsidetheC++ObjectModel.AddisonWesley.ISBN0201834545.
Meyers,Scott(2005).EffectiveC++(Thirded.).AddisonWesley.ISBN0321334876.
Stroustrup,Bjarne(2013).TheC++ProgrammingLanguage(Fourthed.).AddisonWesley.ISBN9780321
563842.
Stroustrup,Bjarne(1994).TheDesignandEvolutionofC++.AddisonWesley.ISBN0201543303.
Stroustrup,Bjarne(2014).ProgrammingPrinciplesandPracticeUsingC++(Seconded.).AddisonWesley.
ISBN9780321992789.
Sutter,Herb(2001).MoreExceptionalC++:40NewEngineeringPuzzles,ProgrammingProblems,and
Solutions.AddisonWesley.ISBN020170434X.
Sutter,Herb(2004).ExceptionalC++Style.AddisonWesley.ISBN0201760428.
Vandevoorde,DavidJosuttis,NicolaiM.(2003).C++Templates:ThecompleteGuide.AddisonWesley.
ISBN0201734842.

Externallinks
JTC1/SC22/WG21(http://www.open
Wikibookshasabookon
std.org/jtc1/sc22/wg21/)theISO/IECC++Standard
thetopicof:MoreC++
WorkingGroup
Idioms
n3242.pdf(http://www.open
std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf)lastpubliclyavailableCommitteeDraft
of"ISO/IECIS14882ProgrammingLanguagesC++"(28February2011)
n3337.pdf(http://www.openstd.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf)firstdraft
aftertheC++11standard,containstheC++11standardplusminoreditorialchanges.
StandardC++Foundation(http://isocpp.org/)anonprofitorganizationthatpromotestheuseand

understandingofstandardC++.BjarneStroustrupisadirectoroftheorganization
ApaperbyStroustrupshowingthetimelineofC++evolution(19912006)
(http://www.stroustrup.com/hoplalmostfinal.pdf)
BjarneStroustrup'sC++StyleandTechniqueFAQ(http://www.stroustrup.com/bs_faq2.html)
C++FAQLitebyMarshallCline(http://www.parashift.com/c%2B%2Bfaqlite/)
Hamilton,Naomi(25June2008)."TheAZofProgrammingLanguages:C++".Computerworld.an
interviewwithBjarneStroustrup
Kalev,Danny(15August2008)."TheStateoftheLanguage:AnInterviewwithBjarneStroustrup".
DevX(QuinStreetInc.).
Katdare,Kaustubh(1February2008)."Dr.BjarneStroustrupInventorofC++".CrazyEngineers.
Stroustrup,Bjarne(8April2015)."ComputerHistoryMuseum:OralHistoryofBjarneStroustrup".
CodepracticesfornotbreakingbinarycompatibilitybetweenreleasesofC++libraries
(http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++)(fromtheKDEtechbase)
OptimizingsoftwareinC++(http://www.agner.org/optimize/optimizing_cpp.pdf)anoptimization
guideforWindows,LinuxandMacplatforms,byAgnerFog
Retrievedfrom"https://en.wikipedia.org/w/index.php?title=C%2B%2B&oldid=682573898"
Categories: Algolprogramminglanguagefamily C++ C++programminglanguagefamily
Classbasedprogramminglanguages Crossplatformsoftware Objectorientedprogramminglanguages
Programminglanguagescreatedin1983 ProgramminglanguageswithanISOstandard
Staticallytypedprogramminglanguages
Thispagewaslastmodifiedon24September2015,at15:47.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicenseadditionaltermsmay
apply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.Wikipediaisa
registeredtrademarkoftheWikimediaFoundation,Inc.,anonprofitorganization.

You might also like