Pages - Menu

Monday, September 30, 2013

Information About C++

Information about C++
About C++
C++ (pronounced "see and plus") could be a programing language that's general purpose, statically written,free-form, multi-paradigm andcompiled. it's considered associate degree intermediate-level language, because it contains each high-level and low-level language options. Developed by Bjarne Stroustrupstarting in 1979 at Bell Labs, C++ was originally named C with categories, adding object orientedfeatures, like categories, and alternative enhancements to the C programing language. The language was renamed C++ in 1983, as a pun involving theincrement operator.
C++ is one in every of the foremost standard programming languages and is enforced on a large type of hardware and OS platforms. As associate degree economic
al compiler to native code, its application domains embrace systems program, application computer code, device drivers, embedded computer code, superior server and consumer applications, and amusement computer code like video games. many teams give each free and proprietary C++ compiler computer code, together with the antelope Project, LLVM, Microsoftand Intel. C++ has greatly influenced several alternative standard programming languages, most notably C# and Java.
C++ is additionally used for hardware style, wherever the look is at the start delineated  in C++, then analyzed, architecturally forced, and regular to form aregister-transfer level hardware description language via high-level synthesis.
The language began as enhancements to C, initial adding categories, then virtual functions, operator overloading, multiple inheritance, templates and exception handling, among alternative options. once years of development, the C++ programing language commonplace was legal in 1998 as ISO/IEC 14882:1998. the quality was amended by the 2003 technical mistake, ISO/IEC 14882:2003. the present commonplace extending C++ with new options was legal and revealed by ISO in Sep 2011 as ISO/IEC 14882:2011 (informally called C++11).


History


Bjarne Stroustrup, a Danish and British trained man of science, began his work on "C with Classes" in 1979. the concept of making a brand new language originated from Stroustrup's expertise in programming for his pH.D. thesis. Stroustrup found that Simula had options that were terribly useful for giant computer code development, however the language was too slow for sensible use, whereas BCPL was quick however too low-level to be appropriate for giant computer code development. once Stroustrup started operating in AT&T Bell Labs, he had the matter of analyzing the UNIXkernel with relevancy distributed computing. memory his pH.D. experience, Stroustrup started out to boost the C language with Simula-like options. C was chosen as a result of it absolutely was all-purpose, fast, moveable and wide used. Besides C and Simula, another languages that impressed him were ALGOL sixty eight, Ada, CLU and ML. At first, the class, derived category, robust writing, inlining, and default argument options were extra to C via Stroustrup's "C with Classes" to compiler, Cpre.
In 1983, the name of the language was modified from C with categories to C++ (++ being the increment operator in C). New options were extra includingvirtual functions, perform name and operator overloading, references, constants, user-controlled free-store memory management, improved sort checking, and BCPL vogue single-line comments with 2 forward slashes (//), additionally because the development of a correct compiler for C++, Cfront. In 1985, the primary edition of The C++ programing language was discharged, providing a very important relevancy the language, as there wasn't however a political candidate commonplace. the primary business implementation of C++ was discharged in Oct of an equivalent year. Release 2.0 of C++ came in 1989 and therefore the updated second edition ofThe C++ programing language was discharged in 1991. New options enclosed multiple inheritance, abstract categories, static member functions, const member functions, and guarded members. In 1990, The Annotated C++ manual was revealed. This work became the premise for the long run commonplace. Late feature additions enclosed templates, exceptions, namespaces, new casts, and a Boolean sort.
As the C++ language evolved, the quality library evolved with it. the primary addition to the C++ commonplace library was the stream I/O library that provided facilities to exchange the normal C functions like printf and scanf. Later, among the foremost important additions to the quality library, was an oversized quantity of the quality model Library.
It is attainable to jot down object headed or procedural code within the same program in C++. This has caused some concern that some C++ programmers area unit still writing procedural code, however area unit beneath the impression that it's object headed, just because they're mistreatment C++. usually it's associate degree uniting of the 2. This typically causes most issues once the code is revisited or the task is seized by another engineer.
C++ continues to be used and is one in every of the well-liked programming languages to develop skilled applications.

Etymology

According to Stroustrup: "the name signifies the biological process nature of the changes from C". throughout C++'s development amount, the language had been brought up as "new C", then "C with Classes". the ultimate name is attributable toRick Mascitti (mid-1983) and was initial utilized in Gregorian calendar month 1983. once Mascitti was questioned informally in 1992 concerning the naming, he indicated that it absolutely was given in a very tongue-in-cheek spirit. It stems from C's "++" operator (whichincrements the worth of a variable) associate degreed a typical naming convention of mistreatment "+" to point an increased bug. A joke goes that the name itself encompasses a bug: owing to the employment of post-increment, that increments worth|the worth} of the variable however evaluates to the unincremented value, C++ is not any higher than C, and therefore the pre-increment ++C type ought to are used instead. there's no language referred to as "C plus". ABCL/c+ was the name of associate degree earlier, unrelated programing language. a number of alternative languages are named equally to C++, most notably C-- and C#.

Philosophy

Throughout C++'s life, its development and evolution has been informally ruled by a collection of rules that its evolution ought to follow:
•    It should be driven by actual issues and its options ought to be helpful at once in universe programmes.
•    Every feature ought to be implementable (with a fairly obvious thanks to do so).
•    Programmers ought to be absolve to decide their own programming vogue, which vogue ought to be absolutely supported by C++.
•    Allowing a helpful feature is additional necessary than preventing each attainable misuse of C++.
•    It ought to give facilities for organising programmes into well outlined separate elements, and supply facilities for combining individually developed elements.
•    No implicit violations of the kind system (but enable specific violations that are expressly asked for by the programmer).
•    Make user created varieties have equal support and performance to in-built varieties.
•    Any options that you simply don't use you are doing not get hold of (e.g. in performance).
•    There ought to be no language to a lower place C++ (except assembly language).
•    C++ ought to work aboard alternative pre-existing programming languages, instead of being a part of its own separate and incompatible programming surroundings.
•    If what the applied scientist desires to try and do is unknown, enable the applied scientist to specify (provide manual control).

Standardization

In 1998, the C++ standards committee (the ISO/IEC JTC1/SC22/WG21working group) standardized C++ and revealed the international standardISO/IEC 14882:1998 (informally called C++98). for a few years once the official unleash of the quality, the committee processed defect reports, and in 2003 revealed a corrected version of the C++ commonplace, ISO/IEC 14882:2003. In 2005, a technical report, referred to as the "Library Technical Report 1" (often called TR1 for short), was discharged. whereas not a political candidate a part of the quality, it fixed variety of extensions to the quality library, that were expected to be enclosed within the next version of C++.
The latest major revision of the C++ commonplace, C++11, (formerly legendary asC++0x) was approved by ISO/IEC on twelve August 2011. it's been revealed as 14882:2011. There area unit plans for a minor (C++14) and a significant revision (C++17) within the future.
C++14 is that the name being employed for successive revision. C++14 is planned to be alittle extension over C++11, that includes chiefly bug fixes and little enhancements, equally to however C++03 was alittle extension to C++98. whereas the name 'C++14' implies a unleash in 2014, this date isn't fastened.

Operators and operator overloading

C++ provides quite thirty five operators, covering basic arithmetic, bit manipulation, indirection, comparisons, logical operations et al. the majority operators will be full for user-defined varieties, with a number of notable exceptions like member access (. and.*) additionally because the conditional operator. The made set of overloadable operators is central to mistreatment user created varieties in C++ additionally and as simply as in-built varieties (so that the user mistreatment them cannot tell the difference). The overloadable operators are a necessary a part of several advanced C++ programming techniques, such assmart pointers. Overloading associate degree operator doesn't amendment the precedence of calculations involving the operator, nor will it amendment the quantity of quantitys that the operator uses (any operand could but be neglected by the operator, although it'll be evaluated before execution). full "&&" and "||" operators lose their short-circuit analysis property.

Memory management

C++ supports four sorts of memory management:
•    Static memory allocation. A static variable is allotted a price at compile-time, and allotted storage in a very fastened location at the side of the possible code. These area unit declared with the "static" keyword (in the sense of static storage, not within the sense of declaring a category variable).
•    Automatic memory allocation. associate degree automatic variable is just declared with its category name, and storage is allotted on the stack once the worth is allotted. The creator is named once the declaration is dead, the destructor is named once the variable goes out of scope, and once the destructor the allotted memory is mechanically freed.
•    Dynamic memory allocation. Storage will be dynamically allotted on theheap mistreatment manual memory management - usually calls to new anddelete (though old-style C calls like malloc() and free() area unit still supported).
•    With the employment of a library, trash pickup is feasible. The Bohme dustman is often used for this purpose.
The fine management over memory management is analogous to C, however in distinction with languages that shall hide such details from the applied scientist, like Java, Perl, PHP, and Ruby.

Templates

C++ templates change generic programming. C++ supports each perform and sophistication templates. Templates could also be parameterized by varieties, compile-time constants, and alternative templates. Templates area unit enforced by internal representation at compile-time. To instantiate a model, compilers substitute specific arguments for a template's parameters to get a concrete perform or category instance. Some substitutions aren't possible; these area unit eliminated by associate degree overload resolution policy delineated  by the phrase "Substitution failure isn't associate degree error" (SFINAE). Templates area unit a robust tool which will be used for generic programming, model metaprogramming, and code optimisation, however this power implies a price. model use could increase code size, as a result of every model internal representation produces a duplicate of the model code: one for every set of model arguments, however, this is often an equivalent quantity of code that might be generated, or less, that if the code was written by hand. this is often in distinction to run-time generics seen in alternative languages (e.g., Java) wherever at compile-time the kind is erased and one model body is preserved.
Templates area unit completely different from macros: whereas each of those compile-time language options change conditional compilation, templates aren't restricted to lexical substitution. Templates area unit conscious of the linguistics and kind system of their companion language, additionally as all compile-time sort definitions, and may perform high-level operations together with programmatic flow management supported analysis of strictly type-checked parameters. Macros area unit capable of conditional management over compilation supported planned criteria, however cannot instantiate new varieties, recurse, or perform sort analysis and in result area unit restricted to pre-compilation text-substitution and text-inclusion/exclusion. In alternative words, macros will management compilation flow supported pre-defined symbols however cannot, not like templates, severally instantiate new symbols. Templates area unit a tool for static polymorphism (see below) and generic programming.
In addition, templates area unit a compile time mechanism in C++ that's Turing-complete, that means that any computation speakable by a bug will be computed, in some type, by a model metaprogram before runtime.
In summary, a model could be a compile-time parameterized perform or category written while not data of the particular arguments accustomed instantiate it. once internal representation, the ensuing code is comparable to code written specifically for the passed arguments. during this manner, templates give the simplest way to decouple generic, loosely applicable aspects of functions and categories (encoded in models) from specific aspects (encoded in template parameters) while not sacrificing performance owing to abstraction.

Objects

Main article: C++ categories
C++ introduces object-oriented programming (OOP) options to C. It offersclasses, which offer the four options unremarkably gift in OOP (and some non-OOP) languages: abstraction, encapsulation, inheritance, andpolymorphism. One identifying feature of C++ categories compared to categories in alternative programming languages is support for settled destructors, that successively give support for the Resource Acquisition is data format (RAII) construct.

Encapsulation

Encapsulation is that the concealing of {data|of knowledge} to make sure that data structures and operators area unit used as meant and to create the usage model additional obvious to the developer. C++ provides the flexibility to outline categories and functions as its primary encapsulation mechanisms. among a category, members will be declared as either public, protected, or personal to expressly enforce encapsulation. A public member of the category is accessible to any perform. a non-public member is accessible solely to functions that area unit members of that category and to functions and categories expressly granted access permission by the category ("friends"). A protected member is accessible to members of categories that inherit from the category additionally to the category itself and any friends.
The OO principle is that every one of the functions (and solely the functions) that access the inner illustration of a sort ought to be encapsulated among the kind definition. C++ supports this (via member functions and friend functions), however doesn't enforce it: the applied scientist will declare elements or all of the illustration of a sort to be public, and is allowed to create public entities that aren't a part of the illustration of the kind. Therefore, C++ supports not simply OO programming, however alternative weaker decomposition paradigms, likemodular programming.
It is typically thought of sensible observe to create all information personal or protected, and to create public solely those functions that area unit a part of a lowest interface for users of the category. this will hide the small print of knowledge implementation, permitting the designer to later basically amendment the implementation while not dynamic  the interface in any approach.

Inheritance

Inheritance permits one information sort to amass properties of alternative information varieties. Inheritance from a base category could also be declared as public, protected, or private. This access intellectual determines whether or not unrelated and derived categories will access the transmissible public and guarded members of the bottom category. solely public inheritance corresponds to what's typically meant by "inheritance". the opposite 2 forms area unit abundant less oftentimes used. If the access intellectual is omitted, a "class" inherits in private, whereas a "struct" inherits in public. Base categories could also be declared as virtual; this is often referred to as virtual inheritance. Virtual inheritance ensures that just one instance of a base category exists within the inheritance graph, avoiding a number of the anomaly issues of multiple inheritance.
Multiple inheritance could be a C++ feature not found in most alternative languages, permitting a category to be derived from quite one base classes; this enables for additional elaborate inheritance relationships. for instance, a "Flying Cat" category will inherit from each "Cat" and "Flying Mammal". another languages, like C# or Java, accomplish one thing similar (although additional limited) by permitting inheritance of multiple interfaces whereas proscribing the quantity of base categories to 1 (interfaces, not like categories, give solely declarations of member functions, no implementation or member data). associate degree interface as in C# and Java will be outlined in C++ as a category containing solely pure virtual functions, usually called associate degree abstract base category or "ABC". The member functions of such associate degree abstract base category area unit usually expressly outlined within the derived category, not transmissible implicitly. C++ virtual inheritance exhibits associate degree ambiguity resolution feature referred to as dominance.

Polymorphism

Polymorphism allows one common interface for several implementations, and for objects to act otherwise beneath completely different circumstances.
C++ supports many forms of static (compile-time) and dynamic (run-time)polymorphisms. Compile-time polymorphism doesn't leave bound run-time choices, whereas run-time polymorphism generally incurs a performance penalty.

Static polymorphism

Function overloading permits programs to declare multiple functions having an equivalent name (but with completely different arguments). The functions area unit distinguished by the quantity or sorts of their formal parameters. Thus, an equivalent perform name will check with completely different functions reckoning on the context during which it's used. the kind came back by the perform isn't accustomed distinguish full functions and would lead to a compile-time error message.
When declaring a perform, a applied scientist will specify for one or additional parameters a default price. Doing thus permits the parameters with defaults to optionally be omitted once the perform is named, during which case the default arguments are going to be used. once a perform is named with fewer arguments than there area unit declared parameters, specific arguments area unit matched to parameters in left-to-right order, with any unmatched parameters at the tip of the parameter list being allotted their default arguments. In several cases, specifying default arguments in a very single perform declaration is desirable to providing full perform definitions with completely different numbers of parameters.
Templates in C++ give a classy mechanism for writing generic, polymorphic code. especially, through the Curiously continual model Pattern, it's attainable to implement a style of static polymorphism that closely mimics the syntax for dominant virtual functions. as a result of C++ templates area unit type-aware and Turing-complete, they will even be accustomed let the compiler resolve algorithmic conditionals and generate substantial programs throughtemplate metaprogramming. Contrary to some opinion, model code won't generate a bulk code once compilation with the right compiler settings.

Dynamic polymorphism

Inheritance

Variable pointers (and references) to a base category sort in C++ will check with objects of any derived categories of that sort additionally to things specifically matching the variable sort. this enables arrays and other forms of containers to carry tips to objects of differing kinds. as a result of assignment of values to variables typically happens at run-time, this is often essentially a run-time development.
C++ conjointly provides a dynamic_cast operator, that permits the program to soundly try conversion of associate degree object into associate degree object of a additional specific object sort (as opposition conversion to a additional general sort, that is often allowed). This feature depends on run-time sort data (RTTI). Objects legendary to be of a precise specific sort can even be forged to it sort withstatic_cast, a strictly compile-time construct that has no runtime overhead and doesn't need RTTI.

Virtual member functions

Ordinarily, once a perform in a very derived category overrides a perform in a very base category, the perform to decision is set by the kind of the item. A given perform is overridden once there exists no distinction within the range or sort of parameters between 2 or additional definitions of that perform. Hence, at compile time, it's going to not be attainable to see the kind of the item and so the proper perform to decision, given solely a base category pointer; the choice is so suspend till runtime. this is often referred to as dynamic dispatch. Virtual member performs or ways enable the foremost specific implementation of the function to be referred to as, consistent with the particular run-time sort of the item. In C++ implementations, this is often unremarkably done mistreatment virtual perform tables. If the item sort is understood, this could be bypassed by prepending a totally qualified category name before the call, however generally calls to virtual functions area unit resolved at run time.
In addition to straightforward member functions, operator overloads and destructors will be virtual. A general rule of thumb is that if any functions within the category area unit virtual, the destructor ought to be additionally. because the sort of associate degree object at its creation is understood at compile time, constructors, and by extension copy constructors, can't be virtual. yet a state of affairs could arise wherever a duplicate of associate degree object must be created once a pointer to a derived object is passed as a pointer to a base object. In such a case, a typical resolution is to form a clone()(or similar) virtual perform that makes and returns a duplicate of the derived category once referred to as.
A member perform can even be created "pure virtual" by appending it with = 0after the closing parenthesis and before the punctuation. a category containing a pure virtual perform is named associate degree abstract information sort. Objects can't be created from abstract information types; they will solely be derived from. Any derived category inherits the virtual perform as pure and should give a non-pure definition of it (and all alternative pure virtual functions) before objects of the derived category will be created. A program that {attempts|makes associate degree attempt|tries} to form an object of a category with a pure virtual member perform or transmissible pure virtual member perform is ungrammatical.

Standard library

The C++ commonplace consists of 2 parts: the core language and therefore the C++ commonplace Library; that C++ programmers expect on each major implementation of C++, it includes vectors, lists, maps, algorithms (find, for_each, binary_search, random_shuffle, etc.), sets, queues, stacks, arrays, tuples, input/output facilities (iostream; reading from the console input, reading/writing from files), sensible pointers for automatic memory management,regular expression support, multi-threading library, atomics support (allowing a variable to be browse or written to be at the most one thread at a time with none external synchronisation), time utilities (measurement, obtaining current time, etc.), a system for changing error coverage that does not use C++ exceptionsinto C++ exceptions, a random range generator and a rather changed version of the C commonplace library (to build it adjust to the C++ sort system).
A large a part of the C++ library is predicated on the STL. This provides helpful tools as containers (for example vectors and lists), iterators to produce these containers with array-like access and algorithms to perform operations like looking and sorting. moreover (multi)maps (associative arrays) and (multi)sets area unit provided, all of that export compatible interfaces. so it's attainable, mistreatment templates, to jot down generic algorithms that job with any instrumentation or on any sequence outlined by iterators. As in C, the options of thelibrary area unit accessed by mistreatment the #include directive to incorporate a typical header. C++ provides one hundred and five commonplace headers, of that twenty seven area unit deprecated.
The standard incorporates the STL was originally designed by Alexander Stepanov, WHO experimented with generic algorithms and containers for several years. once he started with C++, he finally found a language wherever it absolutely was attainable to form generic algorithms (e.g., STL sort) that perform even higher than, for instance, the C commonplace library qsort, because of C++ options like mistreatment inlining and compile-time binding rather than perform pointers. the quality doesn't check with it as "STL", because it is simply a region of the quality library, however the term remains wide accustomed distinguish it from the remainder of the quality library (input/output streams, internationalisation, medicine, the C library set, etc.).
Most C++ compilers, and every one major ones, give a commonplaces orthodox implementation of the C++ standard library.

Parsing and process C++ ASCII text file

It is comparatively troublesome to jot down an honest C++ computer program with classic parsing algorithms like LALR(1). this is often partially the results of the C++ synchronic linguistics not being LALR. as a result of this, there area unit only a few tools for analyzing or performing arts non-trivial transformations (e.g., refactoring) of existing code. a technique to handle this issue is to decide on a distinct syntax. additional powerful parsers, like GLR parsers, will be well less complicated (though slower).
Parsing (in the literal sense of manufacturing a syntax tree) isn't the foremost troublesome drawback in building a C++ process tool. Such tools should even have an equivalent understanding of the that means of the identifiers within the program as a compiler may need. sensible systems for process C++ should then not solely analyze the supply text, however be ready to resolve for every symbol exactly that definition applies (e.g., they have to properly handle C++'s advanced scoping rules) and what its sort is, additionally because the sorts of larger expressions.
Finally, a sensible C++ process tool should be ready to handle the range of C++ dialects utilized in observe (such as that supported by the antelope Compiler assortment which of Microsoft's Visual C++) and implement acceptable analyzers, ASCII text file transformers, and regenerate supply text. Combining advanced parsing algorithms like GLR with image table construction andprogram transformation machinery will change the development of discretional C++ tools.
Parsers do exist all told major compilers. Despite that just one compiler provides the computer program in a very format appropriate for tool integration, Clang, the computer program is usable as a C++ (or C) library that is prepared for integration into, i.e. an IDE.

Compatibility

Producing a fairly standards-compliant C++ compiler has proved  to be a troublesome task for compiler vendors generally. for several years, {different|totally completely different|completely different} C++ compilers enforced the C++ language to different levels of compliance to the quality, and their implementations varied wide in some areas such aspartial model specialization. Recent releases of hottest C++ compilers support the majority of the C++ 1998 commonplace.
To give compiler vendors larger freedom, the C++ standards committee determined to not dictate the implementation of name mangling, exception handling, and alternative implementation-specific options. The draw back of this call is that code created by completely different compilers is predicted to be incompatible. There were, however, tries to standardize compilers for specific machines or in operation systems (for example C++ ABI), although they appear to be mostly abandoned currently.

Exported templates

One specific purpose of competition is that the export keyword, meant to permit model definitions to be separated from their declarations. the primary wide out there compiler to implement export was Comeau C/C++, in early 2003 (five years once the discharge of the standard); in 2004, the beta compiler ofBorland C++ Builder X was conjointly discharged with export. each of those compilers area unit supported the EDG C++ face. alternative compilers like GCCdo not support it in any respect. starting ANSI C++ by Ivor Horton provides example code with the keyword which will not compile in most compilers, while not relevancy this drawback. Herb Sutter, former caller of the C++ standards committee, suggested that export be faraway from future versions of the C++ commonplace. throughout the March 2010 ISO C++ standards meeting, the C++ standards committee voted to get rid of exported templates entirely from C++11, however reserve the keyword for future use.

With C

For additional details on this subject, see Compatibility of C and C++.
C++ is commonly thought of to be a superset of C, however this is often not strictly true. Most C code will simply be created to compile properly in C++, however there area unit a number of variations that cause some valid C code to be invalid or behave otherwise in C++.
One unremarkably encountered distinction is that C permits implicit conversion fromvoid* to alternative pointer varieties, however C++ doesn't (for sort safety reasons). Another common movableness issue is that C++ defines several new keywords, like new and sophistication, which can be used as identifiers (e.g. variable names) in a very computer programme.
Some incompatibilities are removed by the 1999 revision of the C commonplace (C99), that currently supports C++ options like line comments (//), and declarations mixed with code. On the opposite hand, C99 introduced variety of latest options that C++ failed to support, were incompatible or redundant in C++ (e.g. complex, use the advanced category within the commonplace library instead), like variable-length arrays, native complex-number varieties, selected initializers, compound literals, the Boolean typedef (in C++ it's a basic type) and therefore the prohibit keyword. a number of the C99-introduced options were enclosed within the ulterior version of the C++ commonplace,C++11:
•    C99 preprocessor (including variadic macros, wide/narrow literal concatenation, wider whole number arithmetic)
•    _Pragma()
•    long long
•    __func__
•    Headers:
•    cstdbool (stdbool.h)
•    cstdint (stdint.h)
•    cinttypes (inttypes.h).
To mix C and C++ code, associate degreey perform declaration or definition that's to be referred to as from/used each in C and C++ should be declared with C linkage by putting it among an MD "C"  block. Such a perform might not have faith in options reckoning on name mangling (i.e., perform overloading).