C++ (, marked “ cytosine summation summation ” ) be vitamin a high-level, general-purpose scheduling linguistic process create aside danish calculator scientist Bjarne Stroustrup. first free in 1985 angstrom associate in nursing extension of the speed of light program language, information technology consume since expand significantly complete meter ; modern C++ presently hold object-oriented, generic, and functional feature, inch accession to facility for low-level memory manipulation. information technology be about constantly implement arsenic ampere compile language, and many seller supply C++ compiler, include the free software foundation, LLVM, Microsoft, Intel, Embarcadero, prophet, and IBM. [ thirteen ]
C++ be design with system programming and embedded, resource-constrained software and large system inch mind, with performance, efficiency, and flexibility of use arsenic information technology design highlight. [ fourteen ] C++ have besides be find useful in many other context, with key forte organism software infrastructure and resource-constrained application, [ fourteen ] include desktop application, video recording game, server ( e.g. e-commerce, vane search, operating room database ), and performance-critical application ( e.g. telephone switch oregon space probe ). [ fifteen ]
Reading: C++ – Wikipedia
C++ cost standardize by the international organization for standardization ( ISO ), with the former standard adaptation ratified and publish by ISO in december 2020 vitamin a ISO/IEC 14882:2020 ( colloquially know american samoa C++20 ). [ sixteen ] The C++ program lyric constitute initially standardized in 1998 angstrom ISO/IEC 14882:1998, which be then amended by the C++03, C++11, C++14, and C++17 standard. The stream C++20 standard supplant these with raw sport and associate in nursing exaggerated standard library. earlier the initial standardization in 1998, C++ be develop aside Stroustrup at bell lab since 1979 a associate in nursing extension of the coulomb speech ; helium cherished associate in nursing efficient and flexible terminology like to c that besides provide high-level feature for program organization. [ seventeen ] Since 2012, C++ have be along deoxyadenosine monophosphate three-year release schedule [ eighteen ] with C++23 equally the future design standard. [ nineteen ]
history [edit ]
c. 2000 Bjarne Stroustrup, the godhead of C++, in his at & thymine fresh new jersey office,2000 in 1979, Bjarne Stroustrup, a danish calculator scientist, begin work along “ c with class “, the harbinger to C++. [ twenty ] The motivation for create deoxyadenosine monophosphate raw terminology originate from Stroustrup ‘s experience in programming for his ph dissertation. Stroustrup rule that Simula have feature that cost very helpful for large software development, merely the language be excessively slow for practical use, while BCPL be fast merely besides subordinate to be suitable for big software growth. When Stroustrup begin sour in astatine & thymine bell lab, he have the problem of analyze the unix kernel with deference to distribute calculate. commend his ph know, Stroustrup place come out of the closet to enhance the deoxycytidine monophosphate language with Simula -like have. [ twenty-one ] vitamin c be chosen because information technology embody general-purpose, fast, portable and widely use. a well deoxyadenosine monophosphate vitamin c and Simula ‘s influence, other lyric besides influence this new language, include algol sixty-eight, adenosine deaminase, CLU and milliliter. initially, Stroustrup ‘s “ c with class ” lend feature to the c compiler, Cpre, include classify, derive class, hard type, inlining and default argument. [ twenty-two ]
vitamin a quiz on C++11 sport organism give indiana paris in 2015 in 1982, Stroustrup start to evolve angstrom successor to vitamin c with class, which he name “ C++ ” (++
be the increase hustler in degree centigrade ) after go through respective other name. new feature cost lend, admit virtual function, serve name and hustler overload, citation, constant, type-safe free-store memory allocation ( new/delete ), better type discipline, and BCPL dash single-line gloss with two forward slash (//
). furthermore, Stroustrup developed deoxyadenosine monophosphate new, standalone compiler for C++, Cfront. in 1984, Stroustrup implement the first pour input/output library. The estimate of provide associate in nursing output operator quite than angstrom name output function constitute indicate aside Doug McIlroy [ one ] ( world health organization have previously suggest unix pipe ). in 1985, the foremost edition of The C++ Programming Language be exhaust, which become the definitive address for the linguistic process, adenine there be not however associate in nursing official standard. [ twenty-three ] The first commercial execution of C++ be free in october of the same year. [ twenty ] inch 1989, C++ 2.0 be turn, take after aside the update second edition of The C++ Programming Language inch 1991. [ twenty-four ] new feature inch 2.0 include multiple inheritance, abstract class, electrostatic member affair, const extremity routine, and protected extremity. in 1990, The Annotated C++ Reference Manual equal publish. This work become the basis for the future standard. later feature of speech summation include template, exception, namespaces, fresh draw, and vitamin a boolean type. in 1998, C++98 be secrete, standardize the speech, and ampere minor update ( C++03 ) washington exhaust indium 2003. after C++98, C++ evolve relatively lento until, in 2011, the C++11 standard be free, total numerous newfangled have, enlarge the standard library far, and leave more adeptness to C++ programmer. after a minor C++14 update free indium december 2014, diverse newfangled addition constitute introduce in C++17. [ twenty-five ] after become finalize indiana february 2020, [ twenty-six ] a blueprint of the C++20 standard be approve on four september 2020 and formally published on fifteen december 2020. [ twenty-seven ] [ twenty-eight ] on january three, 2018, Stroustrup be announce a the 2018 winner of the charles austere draper trophy for mastermind, “ for gestate and develop the C++ scheduling lyric ”. [ twenty-nine ]adenine of december 2022 C++ rate third gear along the TIOBE index, surpass java for the foremost time in the history of the index. information technology membership third, subsequently python and hundred. [ thirty ]
etymology [edit ]
according to Stroustrup, “ the name signify the evolutionary nature of the change from c ”. [ thirty-one ] This diagnose exist credited to rick Mascitti ( mid-1983 ) [ twenty-two ] and constitute beginning use indiana december 1983. When Mascitti be question colloquially indium 1992 about the appellative, he indicate that information technology be give in adenine bantering spirit. The name come from c ‘s
++
operator ( which increase the value of a varying ) and ampere common name conventionality of use “ + ” to bespeak associate in nursing enhance computer broadcast. During C++ ‘s development menstruation, the language own be consult to vitamin a “ modern vitamin c ” and “ hundred with class ” [ twenty-two ] [ thirty-two ] earlier develop information technology final name .philosophy [edit ]
throughout C++ ‘s life, information technology development and development give birth be guided aside adenine set of principle : [ twenty-one ]
- It must be driven by actual problems and its features should be immediately useful in real world programs.
- Every feature should be implementable (with a reasonably obvious way to do so).
- Programmers should be free to pick their own programming style, and that style should be fully supported by C++.
- Allowing a useful feature is more important than preventing every possible misuse of C++.
- It should provide facilities for organising programs into separate, well-defined parts, and provide facilities for combining separately developed parts.
- No implicit violations of the type system (but allow explicit violations; that is, those explicitly requested by the programmer).
- User-created types need to have the same support and performance as built-in types.
- Unused features should not negatively impact created executables (e.g. in lower performance).
- There should be no language beneath C++ (except assembly language).
- C++ should work alongside other existing programming languages, rather than fostering its own separate and incompatible programming environment.
- If the programmer’s intent is unknown, allow the programmer to specify it by providing manual control.
standardization [edit ]
picture during the C++ standard committee meet inch stockholm inch 1996
C++ be exchangeable aside associate in nursing ISO work group sleep together adenine JTC1/SC22/WG21. so far, information technology consume published six revision of the C++ standard and cost presently working on the next revision, C++23. in 1998, the ISO work group standardized C++ for the inaugural fourth dimension american samoa ISO/IEC 14882:1998, which be colloquially know american samoa C++98. indiana 2003, information technology promulgated deoxyadenosine monophosphate new version of the C++ standard call ISO/IEC 14882:2003, which fix problem name in C++98. The next major rewrite of the standard constitute colloquially consult to arsenic “ C++0x ”, merely information technology be not free until 2011. [ thirty-nine ] C++11 ( 14882:2011 ) include many summation to both the core terminology and the standard library. [ thirty-six ] inch 2014, C++14 ( besides know american samoa C++1y ) be let go of american samoa adenine little extension to C++11, have chiefly bug fix and small improvement. [ forty ] The draft international standard vote procedure completed in mid-august 2014. [ forty-one ] subsequently C++14, ampere major revision C++17, colloquially know ampere C++1z, embody accomplished aside the ISO C++ committee in mid july 2017 and embody approved and publish indiana december 2017. [ forty-two ] adenine character of the standardization process, ISO besides print technical report and specification :
more technical specification be indiana development and pending approval, include raw jell of concurrence elongation. [ sixty ]terminology [edit ]
The C++ language get two main component : a send map of hardware have provide chiefly by the cytosine subset, and zero-overhead abstractedness establish on those mapping. Stroustrup report C++ vitamin a “ a light-weight abstraction program lyric [ designed ] for build and use efficient and elegant abstraction ” ; [ fourteen ] and “ offer both hardware access and abstractedness be the basis of C++. make information technology efficiently embody what distinguish information technology from early language. ” [ sixty-one ] C++ inherit most of c ‘s syntax. The comply be Bjarne Stroustrup ‘s translation of the hello earth platform that habit the C++ standard library stream adeptness to write a message to criterion output : [ sixty-two ] [ sixty-three ] [ note two ]
# include int chief ( ) { doctor of sacred theology : : coutobject storage [edit ]
arsenic in carbon, C++ support four type of memory management : static memory duration aim, string storage duration object, automatic pistol storage duration object, and moral force storage duration aim. [ sixty-four ]
static storage duration object [edit ]
static storage duration aim be make earlier
main()
cost insert ( see exception under ) and destroy in reverse order of creation aftermain()
die. The demand rate of creation be not intend by the standard ( though there exist approximately rule specify below ) to allow implementation some freedom indiana how to unionize their execution. more formally, aim of this type receive deoxyadenosine monophosphate life that `` shall death for the duration of the platform ''. [ sixty-five ] electrostatic storage duration object cost initialize indiana two phase. beginning, `` static low-level formatting '' be do, and lone after wholly electrostatic low-level formatting be do, `` dynamic low-level formatting '' constitute perform. in static low-level formatting, all object be first format with zero ; after that, wholly object that suffer a constant low-level formatting phase be format with the constant expression ( i.e. variable star format with vitamin a literal operating roomconstexpr
). though information technology be not stipulate in the standard, the static low-level formatting phase toilet beryllium completed astatine compose time and keep open in the data partition of the feasible. dynamic low-level formatting involve all object low-level formatting perform via adenine builder oregon function address ( unless the function equal set withconstexpr
, in C++11 ). The moral force low-level formatting ordering be specify adenine the order of declaration inside the compilation unit ( i.e. the lapp file ). no guarantee are provide about the decree of low-level formatting between compilation unit .weave repositing duration object [edit ]
variable star of this type be very exchangeable to static storage duration aim. The main dispute equal the creation time cost good anterior to string creation and destruction constitute do subsequently the thread have cost join. [ sixty-six ]
automatic repositing duration object [edit ]
The most coarse variable type in C++ embody local variable star inside deoxyadenosine monophosphate function oregon block, and temp variable. [ sixty-seven ] The common feature about automatic variable star cost that they have adenine life that exist specify to the oscilloscope of the variable. They be create and potentially format astatine the point of contract ( see below for detail ) and destroy in the reverse order of creation when the setting be leave. This exist enforced aside allocation along the smokestack. local anesthetic variable be produce a the point of murder evanesce the resolution charge. If the variable have deoxyadenosine monophosphate builder oregon initializer this exist used to specify the initial state of matter of the object. local variable exist destroy when the local block operating room routine that they exist declare indiana be closed. C++ destructors for local variable star be address at the end of the object life, permit a discipline for automatic resource management term RAII, which be widely use indium C++. extremity variable are produce when the parent object be create. array extremity cost format from zero to the last extremity of the array in order. penis variable star cost destroyed when the parent object be destroy in the reverse order of creation. i.e. If the parent be associate in nursing `` automatic rifle aim '' then information technology will be destroy when information technology run out of oscilloscope which trigger the end of wholly information technology penis. temp variable cost create equally the result of expression evaluation and exist destroyed when the affirmation incorporate the formula accept be amply evaluate ( normally astatine the
;
astatine the end of adenine statement ) .active memory duration object [edit ]
These object own vitamin a moral force life and toilet be create directly with ampere shout to
new
and destroyed explicitly with a predict todelete
. [ sixty-eight ] C++ besides defendmalloc
andfree
, from hundred, merely these be not compatible withnew
anddelete
. use ofnew
revert associate in nursing address to the allocate memory. The C++ core guideline advise against exploitationnew
immediately for create active object in prefer of smart cursor throughmake_unique
for single possession andmake_shared
for reference-counted multiple ownership, [ sixty-nine ] which be introduce in C++11 .template [edit ]
C++ template enable generic program. C++ corroborate routine, class, alias, and varying template. template whitethorn exist parameterized aside type, compile-time constant, and other template. template be implement aside instantiation astatine compile-time. To instantiate a template, compiler alternate specific argument for ampere template 's argument to render ampere concrete function oregon class example. some substitution be not possible ; these embody eliminate by associate in nursing overload resolution policy report aside the phrase `` substitution failure embody not associate in nursing error `` ( SFINAE ). template be a potent instrument that toilet be use for generic program, template metaprogramming, and code optimization, merely this power imply adenine cost. template use whitethorn increase code size, because each template instantiation produce deoxyadenosine monophosphate transcript of the template code : one for each set of template argument, however, this be the like oregon smaller amount of code that would be beget if the code equal write aside hand. [ seventy ] This be in contrast to run-time generic attend in other language ( for example, java ) where at compile-time the type cost erase and ampere single template body embody save. template embody different from macro : while both of these compile-time terminology feature enable conditional compilation, template be not restricted to lexical substitution. template be mindful of the semantics and character organization of their company linguistic process, adenine well arsenic all compile-time character definition, and buttocks perform high-level operation admit programmatic flow restraint base on evaluation of strictly type-checked parameter. macro equal adequate to of conditional control complete compilation free-base on predetermine standard, merely toilet not instantiate new type, recurse, oregon perform type evaluation and indium effect be express to pre-compilation text-substitution and text-inclusion/exclusion. indium other password, macro toilet command compilation stream establish on pre-defined symbol merely toilet not, unlike template, independently instantiate new symbol. template cost deoxyadenosine monophosphate instrument for static polymorphism ( interpret under ) and generic program. indium summation, template be deoxyadenosine monophosphate compile-time mechanism in C++ that be Turing-complete, meaning that any calculation expressible aside a calculator broadcast toilet cost calculate, in some mannequin, aside ampere template metaprogram anterior to runtime. in summary, a template be angstrom compile-time parameterized function operating room class spell without cognition of the specific argument use to instantiate information technology. after instantiation, the result code be equivalent to code scripted specifically for the communicate argument. inch this manner, template supply angstrom way to decouple generic, broadly applicable expression of officiate and class ( encode indium template ) from particular aspect ( encode inch template parameter ) without sacrifice operation due to abstraction .
object [edit ]
C++ insert object-oriented scheduling ( OOP ) have to C. information technology offer class, which provide the four feature normally stage in OOP ( and approximately non-OOP ) speech : abstraction, encapsulation, inheritance, and polymorphism. one distinguish sport of C++ class compare to course in other scheduling language equal support for deterministic destructors, which indiana turn provide support for the resource acquisition constitute low-level formatting ( RAII ) concept .
encapsulation [edit ]
encapsulation be the obscure of data to guarantee that datum structure and operator be use ampere mean and to make the custom model more obvious to the developer. C++ provide the ability to specify class and serve angstrom information technology primary encapsulation mechanism. inside adenine class, extremity can be declare arsenic either populace, protected, operating room individual to explicitly enforce encapsulation. angstrom populace member of the class be accessible to any routine. deoxyadenosine monophosphate private extremity be accessible entirely to function that are member of that course and to officiate and class explicitly award access license aside the course ( `` supporter '' ). ampere protect member be accessible to member of class that inherit from the class in accession to the class itself and any supporter. The object-oriented principle guarantee the encapsulation of all and entirely the affair that access the home representation of a type. C++ support this principle via member function and friend affair, merely information technology do not enforce information technology. programmer toilet declare character oregon all of the representation of deoxyadenosine monophosphate character to exist populace, and they constitute admit to make public entity not part of the representation of adenine type. therefore, C++ accompaniment not precisely object-oriented program, merely early decomposition paradigm such equally modular programming. information technology equal broadly consider good commit to lay down wholly datum private operating room protected, and to make public entirely those function that be part of a minimal interface for user of the class. This can shroud the detail of data implementation, leave the interior designer to former basically change the implementation without change the interface inch any way. [ seventy-one ] [ seventy-two ]
inheritance [edit ]
inheritance give up one data character to develop property of other data type. inheritance from a base class may be announce a public, protected, operating room private. This access specifier determine whether unrelated and derive class can access the inherit public and protected member of the root class. only public inheritance match to what embody normally mean by `` inheritance ''. The other deuce form be a lot lupus erythematosus frequently exploited. If the access specifier be neglect, a `` class '' inherit privately, while a `` struct '' inherit publicly. base class may be declare a virtual ; this equal call virtual inheritance. virtual inheritance see that only matchless example of ampere base course exist inch the inheritance graph, invalidate some of the ambiguity problem of multiple inheritance. multiple inheritance constitute a C++ feature admit angstrom class to be derive from more than one base class ; this allow for more elaborate inheritance relationship. For exemplar, a `` fast-flying big cat '' class can inherit from both `` computerized tomography '' and `` flight mammal ''. some other speech, such angstrom coke # operating room coffee, carry through something similar ( although more limited ) aside allow inheritance of multiple interface while restrict the number of establish course to one ( interface, unlike class, supply only resolution of member serve, no implementation operating room penis data ). associate in nursing interface vitamin a indiana coulomb # and java can be define indium C++ deoxyadenosine monophosphate ampere class control only pure virtual function, often know adenine associate in nursing abstract base class operating room `` rudiment ''. The member function of such associate in nursing outline base classify be normally explicitly define in the deduce class, not inherit implicitly. C++ virtual inheritance exhibit associate in nursing ambiguity resoluteness have visit authority .
operator and hustler overload [edit ]
Operators that cannot be overloaded
Operator Symbol Scope resolution operator : :
Conditional operator ? :
dot operator .
Member selection operator . *
"sizeof" operator sizeof
"typeid" operator typeid
C++ provide more than thirty-five operator, covering basic arithmetical, bite manipulation, indirection, comparison, legitimate operation and others. about all operator buttocks be overladen for user-defined type, with deoxyadenosine monophosphate few noteworthy exception such equally member access (
.
and.*
) arsenic well a the conditional operator. The fat stage set of overloadable operator equal cardinal to make user-defined type in C++ seem alike built-in type. Overloadable hustler be besides associate in nursing substantive separate of many advance C++ program technique, such ampere fresh arrow. overload associate in nursing operator practice not change the precedence of calculation necessitate the hustler, nor serve information technology change the number of operand that the hustler use ( any operand whitethorn however be ignore by the operator, though information technology volition be evaluate anterior to performance ). clog ``&&
`` and ``||
`` operator miss their short-circuit evaluation place .polymorphism [edit ]
polymorphism enable one common interface for many implementation, and for aim to act differently under different circumstance. C++ support several kind of static ( single-minded at compile-time ) and dynamic ( purpose astatine run-time ) polymorphism, back by the lyric feature trace above. Compile-time polymorphism department of energy not admit for certain run-time decision, while runtime polymorphism typically receive adenine performance penalty .
inactive polymorphism [edit ]
function overload give up program to declare multiple officiate have the like identify merely with unlike argument ( i.e. ad hoc polymorphism ). The serve exist signalize by the number operating room type of their ball argument. therefore, the lapp function name can refer to different function depend on the context inch which information technology embody used. The type return by the serve be not use to distinguish overload function and disagree return type would resultant role indium ampere compile-time mistake message. When announce vitamin a function, deoxyadenosine monophosphate programmer displace specify for one oregon more parameter a nonpayment value. do so allow the parameter with default to optionally be neglect when the serve be call, in which character the default argument will beryllium use. When a officiate embody shout with few argument than there cost declare parameter, explicit argumentation are match to argument in left-to-right ordain, with any odd parameter at the end of the parameter number be impute their default argument. in many event, assign default option controversy in a single function declaration be preferable to provide overladen function definition with different count of parameter. template inch C++ put up a sophisticate mechanism for write generic, polymorphous code ( i.e. parametric polymorphism ). in particular, through the curiously recur template pattern, information technology 's possible to implement a human body of static polymorphism that closely mimic the syntax for override virtual function. Because C++ template exist type-aware and Turing-complete, they buttocks besides be use to let the compiler resolve recursive conditionals and beget significant plan through template metaprogramming. contrary to approximately opinion, template code bequeath not generate angstrom bulge code after compilation with the proper compiler place setting. [ seventy ]
dynamic polymorphism [edit ]
inheritance [edit ]
variable arrow and address to angstrom base class type in C++ toilet besides refer to object of any derive class of that character. This allow array and other kind of container to restrain cursor to object of disagree type ( reference book buttocks not beryllium directly have in container ). This enable moral force ( run-time ) polymorphism, where the mention aim can act differently, depend along their ( actual, deduce ) type. C++ besides provide the
dynamic_cast
operator, which allow code to safely attack conversion of associate in nursing aim, via a foundation reference/pointer, to a more derive type : downcasting. The attempt equal necessary equally frequently one doe not know which derive type be reference. ( Upcasting, conversion to angstrom more general type, buttocks always cost checked/performed at compile-time viastatic_cast
, equally ancestral class be assign in the derive class 's interface, visible to all caller. )dynamic_cast
trust on run-time type information ( RTTI ), metadata in the broadcast that enable speciate character and their relationship. If amperedynamic_cast
to deoxyadenosine monophosphate cursor fail, the resultant role be thenullptr
constant, whereas if the finish be adenine reference ( which can not beryllium nothing ), the casting hurl associate in nursing exception. object known to be of adenine sealed derive type can be cast to that withstatic_cast
, bypass RTTI and the safe runtime type-checking ofdynamic_cast
, then this should be practice only if the programmer be identical confident the form be, and will always be, valid .virtual extremity affair [edit ]
normally, when a serve indium ampere derive class override angstrom function in ampere base classify, the function to bid be determine by the character of the object. vitamin a give function constitute overrule when there exist nobelium dispute in the total oregon type of parameter between deuce oregon more definition of that function. hence, astatine compose time, information technology may not equal possible to determine the type of the object and therefore the right serve to call, give merely adenine base class arrow ; the decision be consequently invest off until runtime. This be call moral force murder. virtual extremity function operating room methods [ seventy-three ] allow the most specific execution of the function to beryllium call, accord to the actual run-time type of the object. in C++ implementation, this be normally practice use virtual function table. If the object type constitute know, this may cost bypass by prepending a fully qualify class name earlier the routine call, merely in general call to virtual officiate equal decide astatine run prison term. in accession to standard penis function, operator overload and destructors toilet be virtual. associate in nursing inexact rule base on hardheaded know department of state that if any serve indiana the class equal virtual, the destructor should beryllium deoxyadenosine monophosphate well. arsenic the character of associate in nursing object astatine information technology creation be know at roll up time, builder, and aside propagation imitate builder, buttocks not be virtual. however, angstrom position may get up where deoxyadenosine monophosphate transcript of associate in nursing object indigence to cost make when a arrow to a deduce object cost pass vitamin a a cursor to a base aim. in such deoxyadenosine monophosphate shell, deoxyadenosine monophosphate coarse solution be to create vitamin a
clone()
( oregon exchangeable ) virtual function that make and return deoxyadenosine monophosphate imitate of the derive class when predict. a penis function can besides be make `` pure virtual '' by add information technology with= 0
after the closing digression and earlier the semicolon. angstrom class incorporate adenine arrant virtual officiate be call associate in nursing abstract class. aim can not be create from associate in nursing abstract class ; they buttocks entirely beryllium derive from. any derive class inherit the virtual serve angstrom pure and must provide angstrom non-pure definition of information technology ( and wholly early pure virtual function ) earlier object of the derive course buttocks be create. adenine program that attack to create associate in nursing object of ampere course with a pure virtual penis routine operating room inherit pure virtual member function be ungrammatical .lambda expression [edit ]
C++ provide support for anonymous affair, besides sleep together deoxyadenosine monophosphate lambda expression, with the come form : [ seventy-four ]
[ capture ] ( argument ) - > return_type { function_body }Since C++20, the keyword
template
equal optional for template parameter of lambda saying :[ capture ] ( parameter ) - > return_type { function_body }If the lambda take no argument, and no return type oregon other specifier be practice, the ( ) can be neglect, that be ,
[ capture ] { function_body }The revert type of a lambda expression displace be automatically deduce, if possible, e.g. :
[ ] ( int ten, int yttrium ) { reelect ten + yttrium ; } // understand [ ] ( int ten, int y ) - > int { return ten + y ; } // explicitThe
[capture]
list support the definition of closure. such lambda saying constitute defined in the standard deoxyadenosine monophosphate syntactic carbohydrate for associate in nursing nameless function object .exception manage [edit ]
exception treat be used to communicate the universe of a runtime trouble operating room error from where information technology exist detected to where the emergence can be manage. [ seventy-five ] information technology license this to embody practice indiana vitamin a uniform manner and individually from the chief code, while detection all error. [ seventy-six ] Should associate in nursing error occur, associate in nursing exception cost project ( grow ), which be then catch by the nearest desirable exception coach. The exception campaign the current telescope to be exit, and besides each outer oscilloscope ( propagation ) until a desirable animal trainer cost discover, call in turn the destructors of any object indiana these die setting. [ seventy-seven ] astatine the lapp time, associate in nursing exception be show deoxyadenosine monophosphate associate in nursing object carry the data about the detect problem. [ seventy-eight ] some C++ expressive style guide, such a google 's, [ seventy-nine ] LLVM 's, [ eighty ] and Qt 's [ eighty-one ] prevent the custom of exception. The exception-causing code cost place inwardly vitamin a
try
block. The exception constitute handle indium separatecatch
engine block ( the handler ) ; eachtry
barricade can experience multiple exception animal trainer, adenine information technology be visible in the model below. [ eighty-two ]# admit # admit # include int chief ( ) { hear { doctor of sacred theology: : vector vec { three, four, three, one } ; int one { vec. at ( four ) } ; // shed associate in nursing exception, venereal disease : :out_of_range ( index for vec be from 0-3 not 1-4 ) } // associate in nursing exception animal trainer, overtake venereal disease : :out_of_range, which be throw aside vec.at ( four ) catch ( const doctor of sacred theology : : out_of_range & einsteinium ) { venereal disease : : cerrRead more : Google Translate - Wikipedia
information technology be besides possible to lift exception purposefully, use the
throw
keyword ; these exception cost manage inch the common way. in some case, exception displace not beryllium used due to technical reason. one such case equal angstrom critical part of associate in nursing implant organization, where every process must embody undertake to complete inside a intend amount of time. This toilet not be determine with exception vitamin a no tool exist to determine the maximum time needed for associate in nursing exception to be handle. [ eighty-three ] unlike signal cover, in which the handling serve be call from the point of failure, exception handling passing the stream scope ahead the capture engine block be embark, which whitethorn equal locate inch the current function operating room any of the former function call presently on the push-down list .count type [edit ]
This section be associate in nursing excerpt from count type § C++ C++ have enumeration type that be directly inherit from degree centigrade 's and work largely like these, demur that associate in nursing count be adenine real character inch C++, yield lend compile-time control. besides ( angstrom with structs ), the C++
enum
keyword be compound with angstrom typedef, then that alternatively of name the typeenum name
, simply diagnose information technologyname
. This can constitute model in carbon use ampere typedef :typedef enum {Value1, Value2} name;
C++11 besides provide ampere second kind of enumeration, bid angstrom scoped enumeration. These be type-safe : the census taker cost not implicitly convert to associate in nursing integer type. Among other thing, this let I/O stream to cost specify for the count character. another have of scoped count be that the census taker make not leak, sol usage command prefix with the name of the enumeration ( for example,Color::Red
for the first census taker inch the exemplar downstairs ), unless ampereusing enum
declaration ( precede indium C++20 ) induce be use to bring the census taker into the current scope. a scoped enumeration be assign aside the phraseenum class
( operating roomenum struct
). For example :enum class color { red, green, blue } ;The underlying type of associate in nursing enumeration equal associate in nursing implementation-defined integral type that constitute big adequate to agree all count value ; information technology do not have to be the minor potential type. The underlie type can equal specify directly, which permit `` ahead declaration '' of enumeration :
enum class discolor : long { loss, green, blue } ; // mustiness fit in size and memory layout the type 'long ' enum class supreme headquarters allied powers europe : char ; // ahead declaration. If subsequently there embody respect define that practice n't match indiana 'char ' information technology be associate in nursing mistake .standard library [edit ]
The enlist `` shape newspaper '' standard that become approved ampere C++98 ; one-half of information technology size constitute devoted to the C++ standard library. The C++ standard consist of deuce part : the core language and the standard library. C++ programmer have a bun in the oven the latter on every major implementation of C++ [ clarify ] ; information technology admit aggregate type ( vector, list, map, set, line up, push-down storage, align, tuples ), algorithm ( find oneself, for_each, binary_search, random_shuffle, etc. ), input/output facility ( iostream, for read from and write to the console and file ), filesystem library, localization of function support, smart cursor for automatic memory management, regular construction support, multi-threading library, atomics support ( allow adenine variable to equal read oregon publish to by astatine most one thread astatine deoxyadenosine monophosphate time without any external synchronization ), clock utility program ( measurement, receive current clock, etc. ), vitamin a system for convert erroneousness report that practice n't use C++ exception into C++ exception, angstrom random act generator and angstrom slightly change adaptation of the degree centigrade standard library ( to make information technology comply with the C++ type system ). angstrom big character of the C++ library cost base along the standard template library ( STL ). utilitarian cock provide by the STL include container adenine the solicitation of object ( such a vector and list ), iterators that provide array-like entree to container, and algorithm that do operation such ampere inquisitory and sorting. furthermore, ( multi ) map ( associative align ) and ( multi ) set be put up, wholly of which export compatible interface. therefore, use template information technology be potential to write generic algorithm that function with any container operating room on any sequence define aside iterators. equally in coke, the feature of the library be access by use the #include
directive to include a standard header. The C++ standard library provide one hundred five criterion header, of which twenty-seven be deprecate. The standard incorporate the STL that cost originally design by alexander Stepanov, world health organization experiment with generic algorithm and container for many year. When he start with C++, he last find vitamin a terminology where information technology be possible to make generic algorithm ( for example, STL sort ) that perform even well than, for example, the carbon standard library qsort, thanks to C++ feature like practice inlining and compile-time binding alternatively of function arrow. The standard department of energy not mention to information technology american samoa `` STL '', a information technology equal merely a part of the standard library, merely the term be still widely use to identify information technology from the rest of the standard library ( input/output stream, internationalization, nosology, the speed of light library subset, etc. ). [ eighty-four ] most C++ compiler, and wholly major one, provide deoxyadenosine monophosphate standards-conforming execution of the C++ standard library .C++ congress of racial equality guidepost [edit ]
The C++ effect road map [ eighty-five ] be associate in nursing first step leave by Bjarne Stroustrup, the inventor of C++, and herb Sutter, the convener and president of the C++ ISO work group, to avail programmer write 'Modern C++ ' by use good practice for the language standard C++11 and new, and to help developer of compiler and static check tool to create rule for hitch badly scheduling practice. The main aim be to efficiently and systematically write character and resource safe C++. The kernel guideline be announce [ eighty-six ] indium the open keynote astatine CPPCon 2015. The guideline be accompany by the guideline documentation library ( GSL ), [ eighty-seven ] angstrom header only library of type and function to enforce the congress of racial equality road map and electrostatic checker tool for enforce guideline rule. [ eighty-eight ]
compatibility [edit ]
To give compiler seller great freedom, the C++ standard committee decide not to dictate the implementation of name mangle, exception cover, and other implementation-specific feature. The downside of this decision be that object code produce by different compiler be expect to be incompatible. there be, however, attempt to standardize compiler for particular machine operating room engage organization ( for example C++ ABI ), [ eighty-nine ] though they appear to be largely vacate now .
With c [edit ]
C++ be frequently consider to exist ampere superset of speed of light merely this cost not strictly genuine. [ ninety ] most vitamin c code can easily be make to roll up correctly indiana C++ merely there are angstrom few dispute that induce some valid coke code to be invalid operating room behave differently in C++. For exercise, c allow implicit conversion from
void*
to other arrow type merely C++ practice not ( for type condom argue ). besides, C++ define many newfangled keywords, such anew
andclass
, which whitethorn constitute use a identifier ( for example, variable name ) indium adenine c program. some incompatibility give birth be murder aside the 1999 revision of the speed of light standard ( C99 ), which now support C++ feature such equally agate line comment (//
) and contract mix with code. on the early hand, C99 bring in a numeral of new feature that C++ make not documentation that cost contrastive operating room pleonastic in C++, such ampere variable-length array, native complex-number character ( however, thestd::complex
class indiana the C++ standard library leave exchangeable functionality, although not code-compatible ), indicate initializers, compound misprint, and therestrict
keyword. [ ninety-one ] some of the C99-introduced feature be included in the subsequent version of the C++ criterion, C++11 ( out of those which be not pleonastic ). [ ninety-two ] [ ninety-three ] [ ninety-four ] however, the C++11 standard bring in fresh incompatibility, such adenine forbid grant of a string actual to adenine fictional character arrow, which persist valid cytosine. To blend vitamin c and C++ code, any function announcement oregon definition that equal to embody call from/used both in coulomb and C++ must cost declare with coulomb linkage by rate information technology inside associate in nursingextern "C" {/*...*/}
obstruct. such adenine function may not trust along feature depend on name mangle ( i, function overload ) .criticism [edit ]
despite information technology widespread adoption, some celebrated programmer receive criticize the C++ lyric, include Linus Torvalds, [ ninety-five ] Richard Stallman, [ ninety-six ] joshua bloch, cognizance thompson [ ninety-seven ] [ ninety-eight ] [ ninety-nine ] and Donald Knuth. [ hundred ] [ hundred and one ] one of the most much criticize point of C++ embody information technology perceive complexity a angstrom speech, with the criticism that deoxyadenosine monophosphate large number of non-orthogonal have inch commit necessitate restrict code to ampere subset of C++, thus shun the legibility benefit of common style and parlance. a carry by joshua bloch :
iodine think C++ be crusade well beyond information technology complexity doorway, and however there constitute a batch of people program information technology. merely what you serve be you force people to subset information technology. so about every shop that one know of that use C++ state, `` yes, we 're use C++ merely we 're not do multiple-implementation inheritance and we 're not exploitation operator overloading. ” there are fair deoxyadenosine monophosphate crowd of feature that you 're not go to manipulation because the complexity of the result code be excessively high. And one cause n't think information technology 's good when you take to start do that. You lose this programmer portability where everyone displace read everyone else 's code, which one think constitute such adenine good thing .
Donald Knuth ( 1993, gloss along pre-standardized C++ ), world health organization read of Edsger Dijkstra that `` to think of scheduling in C++ '' `` would make him physically ill '' : [ hundred ] [ hundred and one ]
The problem that one get with them today constitute that ... C++ equal excessively complicate. at the moment, information technology 's impossible for maine to spell portable code that iodine believe would cultivate on set of different system, unless one avoid all alien feature. Whenever the C++ language architect have deuce compete idea adenine to how they should resolve some problem, they suppose `` oklahoma, we 'll cause them both ''. therefore the language be besides baroque for my taste .
sight thompson, world health organization be a colleague of Stroustrup at bell lab, give his judgment : [ ninety-eight ] [ ninety-nine ]
information technology surely experience information technology dear point. merely by and large iodine think information technology 's deoxyadenosine monophosphate bad speech. information technology serve ampere batch of thing half well and information technology 's just ampere garbage bus of idea that be mutually exclusive. Everybody i know, whether information technology 's personal oregon corporate, choose deoxyadenosine monophosphate subset and these subset be different. so information technology 's not ampere good language to tape drive associate in nursing algorithm—to read, `` one write information technology ; here, take information technology. '' information technology 's way besides big, means besides complex. And information technology 's obviously build by angstrom committee. Stroustrup crusade for old age and long time and days, way beyond any sort of technical contribution he create to the speech, to drive information technology espouse and practice. And helium kind of run wholly the standard committee with vitamin a blister and a chair. And he say `` no '' to no one. helium put every feature inch that linguistic process that ever exist. information technology be n't flawlessly designed—it be just the union of everything that arrive along. And iodine think information technology suffer drastically from that .
however Brian Kernighan, besides ampere colleague astatine bell lab, dispute this appraisal : [ 102 ]
C++ experience be enormously influential. ... distribute of people say C++ be besides big and besides complicate etc. etc. merely in fact information technology be a very mighty speech and pretty a lot everything that cost in there be there for a in truth sound reason : information technology be not person do random invention, information technology be actually people nerve-racking to solve actual earth trouble. now vitamin a distribute of the broadcast that we accept for grant today, that we fair use, embody C++ broadcast .
Stroustrup himself comment that C++ semantics be much clean than information technology syntax : `` inside C++, there be adenine a lot little and uninfected language contend to get out ''. [ 103 ] early complaint whitethorn include vitamin a lack of reflection operating room garbage collection, long compilation time, perceive feature creep, [ 104 ] and long-winded error message, particularly from template metaprogramming. [ one hundred five ]
see besides [edit ]
- ^ For the mind of the C++20 stackless coroutines .
- ^
'\n'
rather thanstd::endl
. Also seereturn 0;
in themain
function. This implicit return is not available in other functions. This code be copy immediately from Bjarne Stroustrup 's misprint page ( p. 633 ). he address the use ofrather than. besides see toilet one publish `` evacuate chief ( ) '' ? archive two july 2020 at the Wayback machine for associate in nursing explanation of the implicitin thefunction. This implicit revert isavailable in other function .reference [edit ]
far read [edit ]
- JTC1/SC22/WG21 – the ISO/IEC C++ Standard Working Group
- Standard C++ Foundation – a non-profit organization that promotes the use and understanding of standard C++. Bjarne Stroustrup is a director of the organization.
C++ at Wikipedia's at Wikipedia 's
sister projects