C++ is a statically typed,
free-formIn computer programming, a free-form language is a programming language in which the positioning of characters on the page in program text is not significant. Program text does not need to be placed in specific columns as on old punched card systems, and frequently ends of lines are not significant...
,
multi-paradigmProgramming languages can be grouped by the number and types of paradigms supported.-Paradigm summaries:A concise reference for the programming paradigms listed in this article....
,
compiledA compiled language is a programming language whose implementations are typically compilers , and not interpreters ....
, general-purpose
programming languageA programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
. It is regarded as an intermediate-level language, as it comprises a combination of both
high-levelA high-level programming language is a programming language with strong abstraction from the details of the computer. In comparison to low-level programming languages, it may use natural language elements, be easier to use, or be from the specification of the program, making the process of...
and
low-levelIn computer science, a low-level programming language is a programming language that provides little or no abstraction from a computer's instruction set architecture. Generally this refers to either machine code or assembly language...
language features. It was developed by
Bjarne StroustrupBjarne Stroustrup ; born December 30, 1950 in Århus, Denmark) is a Danish computer scientist, most notable for the creation and the development of the widely used C++ programming language...
starting in 1979 at
Bell LabsBell Laboratories is the research and development subsidiary of the French-owned Alcatel-Lucent and previously of the American Telephone & Telegraph Company , half-owned through its Western Electric manufacturing subsidiary.Bell Laboratories operates its...
as an enhancement to the
C languageC is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
. Originally named
C with Classes, the language was later renamed C++ in 1983.
C++ is one of the most popular programming languages with application domains including systems software (such as
Microsoft WindowsMicrosoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...
),
application softwareApplication software, also known as an application or an "app", is computer software designed to help the user to perform specific tasks. Examples include enterprise software, accounting software, office suites, graphics software and media players. Many application programs deal principally with...
, device drivers, embedded software, high-performance server and client applications, and entertainment software such as video games. Several groups provide both free and proprietary C++
compilerA compiler is a computer program that transforms source code written in a programming language into another computer language...
software, including the
GNU ProjectThe GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain...
, Microsoft,
IntelIntel C++ Compiler is a group of C and C++ compilers from Intel Corporation available for GNU/Linux, Mac OS X, and Microsoft Windows....
and
Embarcadero TechnologiesC++Builder is a rapid application development environment, developed by Borland and owned by Embarcadero Technologies, for writing programs in the C++ programming language. C++Builder combines the Visual Component Library and IDE written in Delphi with a C++ compiler...
. C++ has greatly influenced many other popular programming languages, most notably C# and
JavaJava is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
.
C++ is also used for hardware design, where the design is initially described in C++, then analyzed, architecturally constrained, and scheduled to create a register-transfer level
hardware description languageIn electronics, a hardware description language or HDL is any language from a class of computer languages, specification languages, or modeling languages for formal description and design of electronic circuits, and most-commonly, digital logic...
via
high-level synthesisHigh-level synthesis , sometimes referred to as C synthesis, electronic system level synthesis, algorithmic synthesis, or behavioral synthesis, is an automated design process that interprets an algorithmic description of a desired behavior and creates hardware that implements that behavior. The...
.
The language began as enhancements to
CC is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
, first adding
classesIn object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
, then virtual functions,
operator overloadingIn object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
,
multiple inheritanceMultiple inheritance is a feature of some object-oriented computer programming languages in which a class can inherit behaviors and features from more than one superclass....
,
templatesTemplates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one....
, and
exception handlingException handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....
among other features. After years of development, the C++ programming language standard was ratified in 1998 as
ISO/IEC 14882:1998. The standard was amended by the 2003 technical corrigendum,
ISO/IEC 14882:2003. The current standard extending C++ with new features was ratified and published by ISO in September 2011 as
ISO/IEC 14882:2011 (informally known as C++11).
History
Bjarne Stroustrup began work on "C with Classes" in 1979. The idea of creating a new language originated from Stroustrup's experience in programming for his Ph.D. thesis. Stroustrup found that
SimulaSimula is a name for two programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard...
had features that were very helpful for large software development, but the language was too slow for practical use, while
BCPLBCPL is a procedural, imperative, and structured computer programming language designed by Martin Richards of the University of Cambridge in 1966.- Design :...
was fast but too low-level to be suitable for large software development. When Stroustrup started working in AT&T Bell Labs, he had the problem of analyzing the
UNIXUnix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...
kernel with respect to
distributed computingDistributed computing is a field of computer science that studies distributed systems. A distributed system consists of multiple autonomous computers that communicate through a computer network. The computers interact with each other in order to achieve a common goal...
. Remembering his Ph.D. experience, Stroustrup set out to enhance the
CC is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
language with
SimulaSimula is a name for two programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard...
-like features. C was chosen because it was general-purpose, fast, portable and widely used. Besides C and Simula, some other languages that inspired him were
ALGOL 68ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...
,
AdaAda is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...
, CLU and ML. At first, the class, derived class, strong type checking, inlining, and default argument features were added to C via Stroustrup's C++ to C compiler,
CfrontCfront was the original compiler for C++ from around 1983, which converted C++ to C; developed by Bjarne Stroustrup. The preprocessor did not understand all of the language and much of the code was written via translations. Cfront had a complete parser, built symbol tables, and built a tree for...
. The first commercial implementation of C++ was released on 14 October 1985.
In 1983, the name of the language was changed from
C with Classes to C++ (++ being the increment operator in C). New features were added including
virtual functionIn object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature...
s, function name and operator overloading, references, constants, user-controlled free-store memory control, improved type checking, and BCPL style single-line comments with two forward slashes (
//). In 1985, the first edition of
The C++ Programming LanguageThe C++ Programming Language was the first book to describe the C++ programming language, written by the language’s creator, Bjarne Stroustrup, and first published in October 1985...
was released, providing an important reference to the language, since there was not yet an official standard. Release 2.0 of C++ came in 1989 and the updated second edition of
The C++ Programming Language was released in 1991. New features included multiple inheritance, abstract classes, static member functions, const member functions, and protected members. In 1990,
The Annotated C++ Reference Manual was published. This work became the basis for the future standard. Late addition of features included
templateTemplates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one....
s, exceptions,
namespacesA namespace is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols . An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces...
, new casts, and a
Boolean typeIn computer science, the Boolean or logical data type is a data type, having two values , intended to represent the truth values of logic and Boolean algebra...
.
As the C++ language evolved, the standard library evolved with it. The first addition to the C++ standard library was the
stream I/O libraryiostream is a header file which is used for input/output in the C++ programming language. It is part of the C++ standard library. The name stands for Input/Output Stream. In C++ and its predecessor, the C programming language, there is no special syntax for streaming data input or output. Instead,...
which provided facilities to replace the traditional C functions such as
printfPrintf format string refers to a control parameter used by a class of functions typically associated with some types of programming languages. The format string specifies a method for rendering an arbitrary number of varied data type parameter into a string...
and
scanfScanf format string refers to a control parameter used by a class of functions typically associated with some types of programming languages. The format string specifies a method for reading a string into an arbitrary number of varied data type parameter...
. Later, among the most significant additions to the standard library, was large amounts of the
Standard Template LibraryThe Standard Template Library is a C++ software library which later evolved into the C++ Standard Library. It provides four components called algorithms, containers, functors, and iterators. More specifically, the C++ Standard Library is based on the STL published by SGI. Both include some...
.
C++ is sometimes called a hybrid language.
It is possible to write object oriented or procedural code in the same program in C++. This has caused some concern that some C++ programmers are still writing procedural code, but are under the impression that it is object oriented, simply because they are using C++. Often it is an amalgamation of the two. This usually causes most problems when the code is revisited or the task is taken over by another coder.
C++ continues to be used and is one of the preferred programming languages to develop professional applications.
Etymology
According to Stroustrup: "the name signifies the evolutionary nature of the changes from C". During C++'s development period, the language had been referred to as "new C", then "C with Classes". The final name is credited to
Rick MascittiRick Mascitti is a computer science professional who is credited with changing the name of the programming language "C with Classes" to C++. He currently resides in San Rafael, California....
(mid-1983) and was first used in December 1983. When Mascitti was questioned informally in 1992 about the naming, he indicated that it was given in a
tongue-in-cheekTongue-in-cheek is a phrase used as a figure of speech to imply that a statement or other production is humorously intended and it should not be taken at face value. The facial expression typically indicates that one is joking or making a mental effort. In the past, it may also have indicated...
spirit. It stems from C's "++"
operatorProgramming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...
(which increments the
valueIn computer science, a value is an expression which cannot be evaluated any further . The members of a type are the values of that type. For example, the expression "1 + 2" is not a value as it can be reduced to the expression "3"...
of a
variableIn computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
) and a common
naming conventionA naming convention is a convention for naming things. The intent is to allow useful information to be deduced from the names based on regularities. For instance, in Manhattan, streets are numbered, with East-West streets being called "Streets" and North-South streets called "Avenues".-Use...
of using "+" to indicate an enhanced computer program. There is no language called "C plus". ABCL/c+ was the name of an earlier, unrelated programming language.
Standardization
| Year | C++ Standard | Informal name |
| 2011 |
ISO/IEC 14882:2011 |
C++11 |
| 2007 |
ISO/IEC TR 19768:2007 |
C++TR1 |
| 2003 |
ISO/IEC 14882:2003 |
C++03 |
| 1998 |
ISO/IEC 14882:1998 |
C++98 |
In 1998, the C++ standards committee (the
ISOThe International Organization for Standardization , widely known as ISO, is an international standard-setting body composed of representatives from various national standards organizations. Founded on February 23, 1947, the organization promulgates worldwide proprietary, industrial and commercial...
/
IECThe International Electrotechnical Commission is a non-profit, non-governmental international standards organization that prepares and publishes International Standards for all electrical, electronic and related technologies – collectively known as "electrotechnology"...
JTC1/SC22/WG21SC22, or to give it its full title ISO/IEC JTC1/SC22 Programming languages, their environments and system software interfaces, is the international standardization subcommittee for programming languages, their environments and system software interfaces...
working groupA working group is an interdisciplinary collaboration of researchers working on new research activities that would be difficult to develop under traditional funding mechanisms . The lifespan of the WG can last anywhere between a few months and several years...
) standardized C++ and published the international standard
ISO/IEC 14882:1998 (informally known as
C++98). For some years after the official release of the standard, the committee processed defect reports, and published a corrected version of the C++ standard,
ISO/IEC 14882:2003, in 2003. In 2005, a technical report, called the "
Library Technical Report 1C++ Technical Report 1 is the common name for ISO/IEC TR 19768, C++ Library Extensions, which was a document proposing additions to the C++ standard library for the C++03 language standard. The additions include regular expressions, smart pointers, hash tables, and random number generators. TR1...
" (often known as TR1 for short), was released. While not an official part of the standard, it specified a number of extensions to the standard library, which were expected to be included in the next version of C++. Support for TR1 is growing in almost all currently maintained C++ compilers.
The latest major revision of the C++ standard, C++11, (formerly known as
C++0xC++11, also formerly known as C++0x, is the name of the most recent iteration of the C++ programming language, replacing C++03, approved by the ISO as of 12 August 2011...
) was approved by ISO/IEC on 12 August 2011. It has been published as 14882:2011.
Philosophy
In
The Design and Evolution of C++The Design and Evolution of C++ is a book by Bjarne Stroustrup about the birth of the computer programming language C++.-External links:*...
(1994), Bjarne Stroustrup describes some rules that he used for the design of C++:
- C++ is designed to be a statically typed, general-purpose language that is as efficient and portable as C
- C++ is designed to directly and comprehensively support multiple programming styles (procedural programming
Procedural programming can sometimes be used as a synonym for imperative programming , but can also refer to a programming paradigm, derived from structured programming, based upon the concept of the procedure call...
, data abstraction, object-oriented programmingObject-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
, and generic programmingIn a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
)
- C++ is designed to give the programmer
A programmer, computer programmer or coder is someone who writes computer software. The term computer programmer can refer to a specialist in one area of computer programming or to a generalist who writes code for many kinds of software. One who practices or professes a formal approach to...
choice, even if this makes it possible for the programmer to choose incorrectly
- C++ is designed to be as compatible with C as possible, therefore providing a smooth transition from C
- C++ avoids features that are platform specific or not general purpose
- C++ does not incur overhead
In computer science, overhead is generally considered any combination of excess or indirect computation time, memory, bandwidth, or other resources that are required to attain a particular goal...
for features that are not used (the "zero-overhead principle")
- C++ is designed to function without a sophisticated programming environment
Inside the C++ Object Model (Lippman, 1996) describes how compilers may convert C++ program
statementsIn computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...
into an in-memory layout. Compiler authors are, however, free to implement the standard in their own manner.
Standard library
The 1998
ANSIThe American National Standards Institute is a private non-profit organization that oversees the development of voluntary consensus standards for products, services, processes, systems, and personnel in the United States. The organization also coordinates U.S. standards with international...
/
ISOThe International Organization for Standardization , widely known as ISO, is an international standard-setting body composed of representatives from various national standards organizations. Founded on February 23, 1947, the organization promulgates worldwide proprietary, industrial and commercial...
C++
standardStandardization is the process of developing and implementing technical standards.The goals of standardization can be to help with independence of single suppliers , compatibility, interoperability, safety, repeatability, or quality....
consists of two parts: the
core languageIn computer programming, the core language is the definition of a programming language plus any standard libraries. Identifiers which are reserved for core usage are known as "keywords". The C standard runtime library and the core Java packages are two examples of components of their respective...
and the
C++ Standard LibraryIn C++, the C++ Standard Library is a collection of classes and functions, which are written in the core language and part of the C++ ISO Standard itself...
; the latter includes most of the
Standard Template LibraryThe Standard Template Library is a C++ software library which later evolved into the C++ Standard Library. It provides four components called algorithms, containers, functors, and iterators. More specifically, the C++ Standard Library is based on the STL published by SGI. Both include some...
(STL) and a slightly modified version of the C standard library. Many C++ libraries exist that are not part of the standard, and, using linkage specification, libraries can even be written in languages such as
BASICBASIC is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use - the name is an acronym from Beginner's All-purpose Symbolic Instruction Code....
,
CC is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
,
FortranFortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...
, or
PascalPascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...
. Which of these are supported is compiler-dependent.
The C++ standard library incorporates the C standard library with some small modifications to make it optimized with the C++ language. Another large part of the C++ library is based on the STL. This provides such useful tools as
containerIn computer science, a container is a class, a data structure, or an abstract data type whose instances are collections of other objects. In other words; they are used for storing objects in an organized way following specific access rules...
s (for example vectors and
listsIn computer science, a linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a datum and a reference to the next node in the sequence; more complex variants add additional links...
),
iteratorIn computer programming, an iterator is an object that enables a programmer to traverse a container. Various types of iterators are often provided via a container's interface...
s to provide these containers with array-like access and
algorithmIn mathematics and computer science, an algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function. Algorithms are used for calculation, data processing, and automated reasoning...
s to perform operations such as searching and sorting. Furthermore (multi)maps (
associative arrayIn computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....
s) and (multi)sets are provided, all of which export compatible interfaces. Therefore it is possible, using templates, to write generic algorithms that work with any container or on any sequence defined by iterators. As in C, the
featureThe Institute of Electrical and Electronics Engineers defines the term feature in IEEE 829 as "A distinguishing characteristic of a software item ." - Feature-rich :...
s of the library are accessed by using the
#include directiveIn computer programming, the term directive is applied in a variety of ways that are similar to the term command. It is also used to describe some programming language constructs ....
to include a standard header. C++ provides 72 standard headers, of which 17 are deprecated.
The STL was originally a third-party library from
HPHewlett-Packard Company or HP is an American multinational information technology corporation headquartered in Palo Alto, California, USA that provides products, technologies, softwares, solutions and services to consumers, small- and medium-sized businesses and large enterprises, including...
and later
SGISilicon Graphics, Inc. was a manufacturer of high-performance computing solutions, including computer hardware and software, founded in 1981 by Jim Clark...
, before its incorporation into the C++ standard. The standard does not refer to it as "STL", as it is merely a part of the standard library, but many people still use that term to distinguish it from the rest of the library (input/output streams, internationalization, diagnostics, the C library subset, etc.).
Most C++ compilers provide an implementation of the C++ standard library, including the STL. Compiler-independent implementations of the STL, such as STLPort, also exist. Other projects also produce various custom implementations of the C++ standard library and the STL with various design goals.
Language features
C++ inherits most of C's syntax. The following is Bjarne Stroustrup's version of the
Hello world programA "Hello world" program is a computer program that outputs "Hello world" on a display device. Because it is typically one of the simplest programs possible in most programming languages, it is by tradition often used to illustrate to beginners the most basic syntax of a programming language, or to...
that uses the
C++ standard libraryIn C++, the C++ Standard Library is a collection of classes and functions, which are written in the core language and part of the C++ ISO Standard itself...
stream facility to write a message to standard output:
- include
int main
{
std::cout << "Hello, world!\n";
}
Within functions that define a non-void return type, failure to return a value before control reaches the end of the function results in
undefined behaviourIn computer programming, undefined behavior is a feature of some programming languages—most famously C. In these languages, to simplify the specification and allow some flexibility in implementation, the specification leaves the results of certain operations specifically undefined.For...
(compilers typically provide the means to issue a diagnostic in such a case). The sole exception to this rule is the
main function, which implicitly returns a value of zero.
Operators and operator overloading
C++ provides more than
35 operatorsThis is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the fourth column "Included in C", dictates whether an operator is also present in C...
, covering basic arithmetic, bit manipulation, indirection, comparisons, logical operations and others. Almost all operators can be
overloadedIn object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
for user-defined types, with a few notable exceptions such as member access (
. and
.*) as well as the conditional operator. The rich set of overloadable operators is central to using C++ as a domain-specific language. The overloadable operators are also an essential part of many advanced C++ programming techniques, such as
smart pointerIn computer science, a smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency...
s. Overloading an operator does not change the precedence of calculations involving the operator, nor does it change the number of operands that the operator uses (any operand may however be ignored by the operator, though it will be evaluated prior to execution). Overloaded "
&&" and "
||" operators lose their short-circuit evaluation property.
Operators that cannot be Overloaded
| Operator |
Symbol |
| Scope Resolution Operator |
|
| Conditional Operator |
|
| Member Selection Operator |
|
| 'sizeof' Operator |
|
Templates
C++ templates enable
generic programmingIn a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
. C++ supports both function and class templates. Templates may be parameterized by types, compile-time constants, and other templates. C++ templates are implemented by
instantiation at compile-time. To instantiate a template, compilers substitute specific arguments for a template's parameters to generate a concrete function or class instance. Some substitutions are not possible; these are eliminated by an overload resolution policy described by the phrase "
Substitution failure is not an errorSubstitution failure is not an error refers to a situation in C++ where an invalid substitution of template parameters is not in itself an error...
" (SFINAE). Templates are a powerful tool that can be used for
generic programmingIn a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
,
template metaprogrammingTemplate metaprogramming is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile-time constants, data structures, and...
, and code optimization, but this power implies a cost. Template use may increase code size, since each template instantiation produces a copy of the template code: one for each set of template arguments. This is in contrast to run-time generics seen in other languages (e.g.
JavaGenerics are a facility of generic programming that was added to the Java programming language in 2004 as part of J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety." A common use of this feature is when using a Java Collection...
) where at compile-time the type is erased and a single template body is preserved.
Templates are different from macros: while both of these compile-time language features enable conditional compilation, templates are not restricted to lexical substitution. Templates are aware of the semantics and type system of their companion language, as well as all compile-time type definitions, and can perform high-level operations including programmatic flow control based on evaluation of strictly type-checked parameters. Macros are capable of conditional control over compilation based on predetermined criteria, but cannot instantiate new types, recurse, or perform type evaluation and in effect are limited to pre-compilation text-substitution and text-inclusion/exclusion. In other words, macros can control compilation flow based on pre-defined symbols but cannot, unlike templates, independently instantiate new symbols. Templates are a tool for static
polymorphismSubtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability to create a variable, a function, or an object that has more than one form. The word derives from the Greek "πολυμορφισμός" meaning "having multiple forms"...
(see below) and
generic programmingIn a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
.
In addition, templates are a compile time mechanism in C++ that is Turing-complete, meaning that any computation expressible by a computer program can be computed, in some form, by a
template metaprogramTemplate metaprogramming is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile-time constants, data structures, and...
prior to runtime.
In summary, a template is a compile-time parameterized function or class written without knowledge of the specific arguments used to instantiate it. After instantiation, the resulting code is equivalent to code written specifically for the passed arguments. In this manner, templates provide a way to decouple generic, broadly applicable aspects of functions and classes (encoded in templates) from specific aspects (encoded in template parameters) without sacrificing performance due to abstraction.
Objects
C++ introduces
object-oriented programmingObject-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
(OOP) features to C. It offers
classIn object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
es, which provide the four features commonly present in OOP (and some non-OOP) languages:
abstractionIn computer science, abstraction is the process by which data and programs are defined with a representation similar to its pictorial meaning as rooted in the more complex realm of human life and language with their higher need of summarization and categorization , while hiding away the...
,
encapsulationIn computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...
,
inheritanceIn object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
, and polymorphism. Objects are instances of classes created at runtime. One distinguishing feature of C++ classes compared to classes in other programming languages is support for deterministic
destructorsIn object-oriented programming, a destructor is a method which is automatically invoked when the object is destroyed...
, which in turn provide support for the Resource Allocation is Initialization concept.
Encapsulation
EncapsulationIn computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...
is the hiding of information in order to ensure that data structures and operators are used as intended and to make the usage model more obvious to the developer. C++ provides the ability to define classes and functions as its primary encapsulation mechanisms. Within a class, members can be declared as either public, protected, or private in order to explicitly enforce encapsulation. A public member of the class is accessible to any function. A private member is accessible only to functions that are members of that class and to functions and classes explicitly granted access permission by the class ("friends"). A protected member is accessible to members of classes that inherit from the class in addition to the class itself and any friends.
The OO principle is that all of the functions (and only the functions) that access the internal representation of a type should be encapsulated within the type definition. C++ supports this (via member functions and friend functions), but does not enforce it: the programmer can declare parts or all of the representation of a type to be public, and is allowed to make public entities that are not part of the representation of the type. Therefore, C++ supports not just OO programming, but other weaker decomposition paradigms, like
modular programmingModular programming is a software design technique that increases the extent to which software is composed of separate, interchangeable components called modules by breaking down program functions into modules, each of which accomplishes one function and contains everything necessary to accomplish...
.
It is generally considered good practice to make all
dataThe term data refers to qualitative or quantitative attributes of a variable or set of variables. Data are typically the results of measurements and can be the basis of graphs, images, or observations of a set of variables. Data are often viewed as the lowest level of abstraction from which...
private or protected, and to make public only those functions that are part of a minimal interface for users of the class. This can hide the details of data implementation, allowing the designer to later fundamentally change the implementation without changing the interface in any way.
Inheritance
InheritanceIn object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
allows one data type to acquire properties of other data types. Inheritance from a base class may be declared as public, protected, or private. This access specifier determines whether unrelated and derived classes can access the inherited public and protected members of the base class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two forms are much less frequently used. If the access specifier is omitted, a "class" inherits privately, while a "struct" inherits publicly. Base classes may be declared as virtual; this is called
virtual inheritanceVirtual inheritance is a topic of object-oriented programming. It is a kind of inheritance in which the part of the object that belongs to the virtual base class becomes common direct base for the derived class and any next class that derives from it...
. Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph, avoiding some of the ambiguity problems of multiple inheritance.
Multiple inheritanceMultiple inheritance is a feature of some object-oriented computer programming languages in which a class can inherit behaviors and features from more than one superclass....
is a C++ feature not found in most other languages, allowing a class to be derived from more than one base classes; this allows for more elaborate inheritance relationships. For example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal". Some other languages, such as C# or
JavaJava is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, accomplish something similar (although more limited) by allowing inheritance of multiple
interfacesIn the field of computer science, an interface is a tool and concept that refers to a point of interaction between components, and is applicable at the level of both hardware and software...
while restricting the number of base classes to one (interfaces, unlike classes, provide only declarations of member functions, no implementation or member data). An interface as in C# and Java can be defined in C++ as a class containing only pure virtual functions, often known as an abstract base class or "ABC". The member functions of such an abstract base class are normally explicitly defined in the derived class, not inherited implicitly. C++ virtual inheritance exhibits an ambiguity resolution feature called
dominance.
Polymorphism
PolymorphismIn computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions...
enables one common interface for many implementations, and for objects to act differently under different circumstances.
C++ supports several kinds of
static (compile-time) and
dynamic (run-time) polymorphisms. Compile-time polymorphism does not allow for certain run-time decisions, while run-time polymorphism typically incurs a performance penalty.
Static polymorphism
Function overloading allows programs to declare multiple functions having the same name (but with different arguments). The functions are distinguished by the number or types of their
formal parameterIn computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...
s. Thus, the same function name can refer to different functions depending on the context in which it is used. The type returned by the function is not used to distinguish overloaded functions and would result in a compile-time error message.
When declaring a function, a programmer can specify for one or more parameters a default value. Doing so allows the parameters with defaults to optionally be omitted when the function is called, in which case the default arguments will be used. When a function is called with fewer arguments than there are declared parameters, explicit arguments are matched to parameters in left-to-right order, with any unmatched parameters at the end of the parameter list being assigned their default arguments. In many cases, specifying default arguments in a single function declaration is preferable to providing overloaded function definitions with different numbers of parameters.
Templates in C++ provide a sophisticated mechanism for writing generic, polymorphic code. In particular, through the
Curiously Recurring Template PatternThe curiously recurring template pattern is a C++ idiom in which a class X derives from a class template instantiation using X itself as template argument...
, it's possible to implement a form of static polymorphism that closely mimics the syntax for overriding virtual functions. Since C++ templates are type-aware and Turing-complete, they can also be used to let the compiler resolve recursive conditionals and generate substantial programs through
template metaprogrammingTemplate metaprogramming is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile-time constants, data structures, and...
. Contrary to some opinion, template code will not generate a bulk code after compilation with the proper compiler settings.
Inheritance
Variable pointers (and references) to a base class type in C++ can refer to objects of any derived classes of that type in addition to objects exactly matching the variable type. This allows arrays and other kinds of containers to hold pointers to objects of differing types. Because assignment of values to variables usually occurs at run-time, this is necessarily a run-time phenomenon.
C++ also provides a
dynamic_cast operator, which allows the program to safely attempt conversion of an object into an object of a more specific object type (as opposed to conversion to a more general type, which is always allowed). This feature relies on
run-time type informationIn programming, RTTI refers to a C++ system that makes information about an object's data type available at runtime. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects...
(RTTI). Objects known to be of a certain specific type can also be cast to that type with
static_cast, a purely compile-time construct that is faster and does not require RTTI.
Virtual member functions
Ordinarily, when a function in a derived class
overridesMethod overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes...
a function in a base class, the function to call is determined by the type of the object. A given function is overridden when there exists no difference in the number or type of parameters between two or more definitions of that function. Hence, at compile time, it may not be possible to determine the type of the object and therefore the correct function to call, given only a base class pointer; the decision is therefore put off until runtime. This is called
dynamic dispatchIn computer science, dynamic dispatch is the process of mapping a message to a specific sequence of code at runtime. This is done to support the cases where the appropriate method can't be determined at compile-time...
. Virtual member functions or
methods allow the most specific implementation of the function to be called, according to the actual run-time type of the object. In C++ implementations, this is commonly done using virtual function tables. If the object type is known, this may be bypassed by prepending a
fully qualified class nameIn computer programming, a fully qualified name is an unambiguous name that specifies which object, function, or variable a call refers to without regard to the context of the call...
before the function call, but in general calls to virtual functions are resolved at run time.
In addition to standard member functions, operator overloads and destructors can be virtual. A general rule of thumb is that if any functions in the class are virtual, the destructor should be as well. As the type of an object at its creation is known at compile time, constructors, and by extension copy constructors, cannot be virtual. Nonetheless a situation may arise where a copy of an object needs to be created when a pointer to a derived object is passed as a pointer to a base object. In such a case, a common solution is to create a
clone (or similar) virtual function that creates and returns a copy of the derived class when called.
A member function can also be made "pure virtual" by appending it with
= 0 after the closing parenthesis and before the semicolon. A class containing a pure virtual function is called an
abstract data type. Objects cannot be created from abstract data types; they can only be derived from. Any derived class inherits the virtual function as pure and must provide a non-pure definition of it (and all other pure virtual functions) before objects of the derived class can be created. A program that attempts to create an object of a class with a pure virtual member function or inherited pure virtual member function is ill-formed.
Parsing and processing C++ source code
It is relatively difficult to write a good C++ parser with classic parsing algorithms such as
LALR(1)In computer science, an LALR parser is a type of LR parser based on a finite-state-automata concept. The data structure used by an LALR parser is a pushdown automaton...
. This is partly because the C++ grammar is not LALR. Because of this, there are very few tools for analyzing or performing non-trivial transformations (e.g.,
refactoringCode refactoring is "disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior", undertaken in order to improve some of the nonfunctional attributes of the software....
) of existing code. One way to handle this difficulty is to choose a different syntax. More powerful parsers, such as
GLR parserA GLR parser is an extension of an LR parser algorithm to handle nondeterministic and ambiguous grammars. First described in a 1984 paper by Masaru Tomita, it has also been referred to as a "parallel parser"...
s, can be substantially simpler (though slower).
Parsing (in the literal sense of producing a syntax tree) is not the most difficult problem in building a C++ processing tool. Such tools must also have the same understanding of the meaning of the identifiers in the program as a compiler might have. Practical systems for processing C++ must then not only parse the source text, but be able to resolve for each identifier precisely which definition applies (e.g. they must correctly handle C++'s complex scoping rules) and what its type is, as well as the types of larger expressions.
Finally, a practical C++ processing tool must be able to handle the variety of C++ dialects used in practice (such as that supported by the
GNU Compiler CollectionThe GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain...
and that of Microsoft's
Visual C++Microsoft Visual C++ is a commercial , integrated development environment product from Microsoft for the C, C++, and C++/CLI programming languages...
) and implement appropriate analyzers, source code transformers, and regenerate source text. Combining advanced parsing algorithms such as GLR with
symbol tableIn computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is associated with information relating to its declaration or appearance in the source, such as its type, scope level and...
construction and
program transformationA program transformation is any operation that takes a computer program and generates another program. In many cases the transformed program is required to be semantically equivalent to the original, relative to a particular formal semantics and in fewer cases the transformations result in programs...
machinery can enable the construction of arbitrary C++ tools.
Compatibility
Producing a reasonably standards-compliant C++ compiler has proven to be a difficult task for compiler vendors in general. For many years, different C++ compilers implemented the C++ language to different levels of compliance to the standard, and their implementations varied widely in some areas such as
partial template specializationPartial template specialization is a particular form of class template specialization. Usually used in reference to the C++ programming language, it allows the programmer to specialize only some arguments of a class template, as opposed to explicit specialization, where all the template arguments...
. Recent releases of most popular C++ compilers support almost all of the C++ 1998 standard.
In order to give compiler vendors greater freedom, the C++ standards committee decided not to dictate the implementation of
name manglingIn compiler construction, name mangling is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages....
,
exception handlingException handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....
, and other implementation-specific features. The downside of this decision is that
object codeObject code, or sometimes object module, is what a computer compiler produces. In a general sense object code is a sequence of statements in a computer language, usually a machine code language....
produced by different
compilerA compiler is a computer program that transforms source code written in a programming language into another computer language...
s is expected to be incompatible. There were, however, attempts to standardize compilers for particular machines or
operating systemAn operating system is a set of programs that manage computer hardware resources and provide common services for application software. The operating system is the most important type of system software in a computer system...
s (for example C++ ABI), though they seem to be largely abandoned now.
Exported templates
One particular point of contention is the
export keyword, intended to allow template definitions to be separated from their declarations. The first widely available compiler to implement
export was
Comeau C/C++Comeau C/C++ is a C and C++ compiler produced by Comeau Computing.The compiler supports several dialects of both the C and C++ languages...
, in early 2003 (five years after the release of the standard); in 2004, the beta compiler of Borland C++ Builder X was also released with
export. Both of these compilers are based on the
EDGThe Edison Design Group is a company that makes compiler frontends . Their frontends are widely used in commercially available compilers and code analysis tools. Users include the Intel C++ compiler, SGI MIPSpro, The Portland Group, and Comeau C++...
C++ front end. Other compilers such as
GCCThe GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain...
do not support it at all.
Beginning ANSI C++ by Ivor Horton provides example code with the keyword that will not compile in most compilers, without reference to this problem.
Herb SutterHerb Sutter is a prominent C++ expert. He is also a book author and a columnist for Dr. Dobb's Journal. He joined Microsoft in 2002 as a platform evangelist for Visual C++ .NET, rising to lead software architect for C++/CLI. Sutter served as secretary and convener of the ISO C++ standards committee...
, former convener of the C++ standards committee, recommended that
export be removed from future versions of the C++ standard. During the March 2010 ISO C++ standards meeting, the C++ standards committee voted to remove exported templates entirely from C++0x, but reserve the keyword for future use.
With C
C++ is often considered to be a superset of
CC is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
, but this is not strictly true. Most C code can easily be made to compile correctly in C++, but there are a few differences that cause some valid C code to be invalid or behave differently in C++.
One commonly encountered difference is that C allows implicit conversion from
void* to other pointer types, but C++ does not. Another common portability issue is that C++ defines many new keywords, such as
new and
class, that may be used as identifiers (e.g. variable names) in a C program.
Some incompatibilities have been removed by the latest
(C99) C standardC99 is a modern dialect of the C programming language. It extends the previous version with new linguistic and library features, and helps implementations make better use of available computer hardware and compiler technology.-History:...
, which now supports C++ features such as line comments (
//), and mixed declarations and code. On the other hand, C99 introduced a number of new features that C++ did not support, such as variable-length arrays, native complex-number types, designated initializers, and compound literals. However, at least some of the C99-introduced features were included in the subsequent version of the C++ standard, C++11:
- C99 preprocessor (including variadic macro
A variadic macro is a feature of the C preprocessor whereby a macro may be declared to accept a varying number of arguments.Variable-argument macros were introduced in the ISO/IEC 9899:1999 revision of the C programming language standard in 1999...
s, wide/narrow literal concatenation, wider integer arithmetic)
-
_Pragma
-
long long
-
__func__
- Headers:
-
cstdbool (stdbool.h)
-
cstdint (stdint.h)
-
cinttypes (inttypes.h).
In order to intermix C and C++ code, any function declaration or definition that is to be called from/used both in C and C++ must be declared with C linkage by placing it within an
extern "C" {/*...*/} block. Such a function may not rely on features depending on name mangling (i.e., function overloading).
Criticism
Due to its large feature set and oft-perceived "strict" syntax, the language is sometimes criticized as being overly complicated and thus difficult to fully master. Because it includes most of the C programming language as a subset, C++ also inherits many of the criticisms leveled at C.
Other criticisms stem from what is missing from C++, such as a lack of "native" multithreading facilities—a feature present in some other languages, including
AdaAda is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...
, C#, and
JavaJava is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
(see Lock). The current C++11 standard addresses this issue by adding direct support for
concurrencyIn computer science, concurrency is a property of systems in which several computations are executing simultaneously, and potentially interacting with each other...
to the language, but at present this is only possible by using operating system calls or third party libraries.
C++ is also sometimes compared unfavorably with languages such as
EiffelEiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...
,
JavaJava is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, or
SmalltalkSmalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
on the basis that it enables programmers to "mix and match"
declarativeIn computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow. Many languages applying this style attempt to minimize or eliminate side effects by describing what the program should accomplish, rather than...
,
functionalIn computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
,
genericIn a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
,
modularModular programming is a software design technique that increases the extent to which software is composed of separate, interchangeable components called modules by breaking down program functions into modules, each of which accomplishes one function and contains everything necessary to accomplish...
, and
procedural programmingProcedural programming can sometimes be used as a synonym for imperative programming , but can also refer to a programming paradigm, derived from structured programming, based upon the concept of the procedure call...
styles with object-oriented programming, rather than strictly enforcing a single style, although C++ is intentionally a
multi-paradigmProgramming languages can be grouped by the number and types of paradigms supported.-Paradigm summaries:A concise reference for the programming paradigms listed in this article....
language.
A widely distributed satirical article portrayed Bjarne Stroustrup, interviewed for a 1998 issue of IEEE's
Computer magazine, confessing that C++ was deliberately designed to be complex and difficult, weeding out amateur programmers and raising the salaries of the few programmers who could master the language. The FAQ section of Stroustrup's personal website contains a denial and a link to the actual interview.
Richard StallmanRichard Matthew Stallman , often shortened to rms,"'Richard Stallman' is just my mundane name; you can call me 'rms'"|last= Stallman|first= Richard|date= N.D.|work=Richard Stallman's homepage...
criticizes C++ for having ambiguous grammar and "gratuitous, trivial, incompatibilities with C (...) that are of no
great benefit".
Linus TorvaldsLinus Benedict Torvalds is a Finnish software engineer and hacker, best known for having initiated the development of the open source Linux kernel. He later became the chief architect of the Linux kernel, and now acts as the project's coordinator...
has said, "C++ is a horrible language. It's made more horrible by the fact that a lot of substandard programmers use it".
Another point of criticism is the feature of
multiple inheritanceMultiple inheritance is a feature of some object-oriented computer programming languages in which a class can inherit behaviors and features from more than one superclass....
, as such ontologies are difficult to maintain.
See also
- The C++ Programming Language
The C++ Programming Language was the first book to describe the C++ programming language, written by the language’s creator, Bjarne Stroustrup, and first published in October 1985...
- Comparison of integrated development environments for C/C++
- Comparison of programming languages
Programming languages are used for controlling the behavior of a machine . Like natural languages, programming languages conform to rules for syntax and semantics.There are thousands of programming languages and new ones are created every year...
- List of C++ compilers
- List of C++ template libraries
- Comparison of Java and C++
This is a comparison of the Java programming language with the C++ programming language.- Design aims :The differences between the C++ and Java programming languages can be traced to their heritage, as they have different design goals....
External links