All About C++: PDF Generated At: Thu, 24 Jul 2014 11:54:01 UTC
All About C++: PDF Generated At: Thu, 24 Jul 2014 11:54:01 UTC
PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information.
PDF generated at: Thu, 24 Jul 2014 11:54:01 UTC
Contents
Articles
C++
13
18
25
32
Const-correctness
34
Virtual function
43
Template (C++)
46
References
Article Sources and Contributors
52
54
Article Licenses
License
55
C++
C++
C++
Paradigm(s)
Designed by
Bjarne Stroustrup
Appeared in
1983
Stable release
Preview release
C++14 / 2014
Typing discipline
Static, Nominative
Major implementations
Influenced by
Influenced
Perl, LPC, Lua, Pike, Ada 95, Java, PHP, D, C99, C#, Falcon, Seed7
Cross-platform (multi-platform)
Filename extension(s)
Website
[1]
C++ (pronounced cee plus plus) is a general purpose programming language. It has imperative, object-oriented and
generic programming features, while also providing the facilities for low level memory manipulation.
It is designed with a bias for systems programming (e.g. embedded systems, operating system kernels), with
performance, efficiency and flexibility of use as its design requirements. C++ has also been found useful in many
other contexts, including desktop applications, servers (e.g. e-commerce, web search, SQL), performance critical
applications (e.g. telephone switches, space probes) and entertainment software, such as video games.
It is a compiled language, with implementations of it available on many platforms. Various organizations provide
them, including the FSF, LLVM, Microsoft and Intel.
C++ is standardised by the International Organization for Standardization (ISO), which the latest (and current)
having being ratified and published by ISO in September 2011 as ISO/IEC 14882:2011 (informally known as
C++11). The C++ programming language was initially standardised in 1998 as ISO/IEC 14882:1998, which was
then amended by the C++03, ISO/IEC 14882:2003, standard. The current standard (C++11) supersedes these, with
new features and an enlarged standard library.
Before standardization (1989 onwards), C++ was developed by Bjarne Stroustrup at Bell Labs, starting in 1979, who
wanted an efficient flexible language (like C) that also provided high level features for programme organization.
Many other programming languages have been influenced by C++, including C#, Java, and newer versions of C
(after 1998).
C++
History
Bjarne Stroustrup, a Danish and British trained computer scientist,
began his work on C++'s predecessor "C with Classes" in 1979. The
motivation for creating a new language originated from Stroustrup's
experience in programming for his Ph.D. thesis. Stroustrup found that
Simula had features that were very helpful for large software
development, but the language was too slow for practical use, while
BCPL 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 UNIX kernel with respect to
Bjarne Stroustrup, creator of C++
distributed computing. Remembering his Ph.D. experience, Stroustrup
set out to enhance the C language with Simula-like features. C was
chosen because it was general-purpose, fast, portable and widely used. As well as C and Simula's influences, other
languages also influenced C++, including, ALGOL 68, Ada, CLU and ML.
Initially, the class, derived class, strong typing, inlining, and default argument features were added to C via
Stroustrup's "C with Classes" to C compiler, Cpre.[2]
In 1983, it was renamed from C with Classes to C++ (++ being the increment operator in C). New features were
added including virtual functions, function name and operator overloading, references, constants, type-safe free-store
memory allocation (new/delete), improved type checking, and BCPL style single-line comments with two forward
slashes (//), as well as the development of a proper compiler for C++, Cfront.
In 1985, the first edition of The C++ Programming Language was released, which became the definitive reference
for the language, as there was not yet an official standard. The first commercial implementation of C++ was released
in October of the same year.
In 1989 C++ 2.0 was released followed by the updated second edition of The C++ Programming Language in 1991.
New features in 2.0 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 feature additions included templates, exceptions, namespaces, new casts, and a boolean
type.
In 2011, C++11 was released which added more features and enlarged the standard library further (compared to it in
1998), providing more facilities for C++ programmers to use, with more additions planned for 2014 and 2017.
Etymology
According to Stroustrup: "the name signifies the evolutionary nature of the changes from C". This name is credited
to Rick Mascitti (mid-1983)[3] 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-cheek spirit. The name stems from C's "++" operator (which increments the value of a variable) and a
common naming convention of using "+" to indicate an enhanced computer program. A joke goes that the name
itself has a bug: due to the use of post-increment, which increments the value of the variable but evaluates to the
unincremented value, so C++ is no better than C, and the pre-increment ++C form should have been used instead, so
that C++ is better than C.
During C++'s development period, the language had been referred to as "new C", then "C with Classes", before
acquiring its final name.
C++
Philosophy
Throughout C++'s life, its development and evolution has been informally governed by a set of rules that its
evolution should follow:
It must be driven by actual problems and its features should be useful immediately in real world programmes.
Every feature should be implementable (with a reasonably obvious way to do so).
Programmers should be free to pick their own programming style, and that style should be fully supported by
C++.
Allowing a useful feature is more important than preventing every possible misuse of C++.
It should provide facilities for organising programmes into well defined separate parts, and provide facilities for
combining separately developed parts.
No implicit violations of the type system (but allow explicit violations that have been explicitly asked for by the
programmer).
Make user created types have equal support and performance to built in types.
Any features that you do not use you do not pay for (e.g. in performance).
There should be no language beneath C++ (except assembly language).
C++ should work alongside other pre-existing programming languages, rather than being part of its own separate
and incompatible programming environment.
If what the programmer wants to do is unknown, allow the programmer to specify (provide manual control).
Standardization
Year
C++ Standard
Informal name
C++98
C++03
C++TR1
C++11
C++ is standardized by an ISO working group, JTC1/SC22/WG21. So far it has seen three versions of C++ released
and is currently working on releasing C++1y.
In 1998, it standardized C++ for the first time as ISO/IEC 14882:1998 (informally known as C++98). In 2003 it then
published a new version of the C++ standard, ISO/IEC 14882:2003, which fixed problems which had been identified
in C++98.
In 2005, a technical report, called the "Library Technical Report 1" (TR1), was released. While not an official part of
the standard, it specified a number of extensions to the standard library, which were then included in the next version
of C++ (then C++0x).
The latest major revision of the C++ standard, C++11 (formerly known as C++0x), was approved and released on the
12 August 2011, as 14882:2011.
A small extension to C++11, C++14 (also known as C++1y) featuring mainly bug fixes and small improvements is
planned for release in 2014. It holds similar aims as C++03 did to C++98.
After C++1y, a major revision, informally known as C++17, is planned for 2017.
C++
Language
C++ inherits most of C's syntax. The following is Bjarne Stroustrup's version of the Hello world program that uses
the C++ Standard Library stream facility to write a message to standard output:
# include <iostream>
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 behaviour (compilers typically provide the means to issue a diagnostic in such a
case).[4] The sole exception to this rule is the main function, which implicitly returns a value of zero.[5]
Symbol
::
Conditional operator
?:
dot operator
Member selection operator
.
.*
"sizeof" operator
sizeof
"typeid" operator
typeid
C++ provides more than 35 operators, covering basic arithmetic, bit manipulation, indirection, comparisons, logical
operations and others. Almost all operators can be overloaded 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 user created types in C++ as well and as easily as built in types (so that the user using them cannot
tell the difference). The overloadable operators are also an essential part of many advanced C++ programming
techniques, such as smart pointers. 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.
Object storage
C++ supports four types of memory management:[6]
C++
5
Static storage duration objects
Static storage duration objects are created before main() (see exceptions below) is entered and destroyed in reverse
order of creation after main() exits. The exact order of creation is not specified by the standard (though there are
some rules defined below) to allow implementations some freedom in how to organize there implementation. More
formally, objects of this type have a lifespan that "shall last for the duration of the program".[7]
Static storage duration objects are initialized in two phases. First, "static initialization" is performed, and only after
all static initialization is performed, "dynamic initialization" is performed:
Static initialization all objects are first zero initialized. Then all objects that have an constant initialization phase
are initialized with the constant expression (ie variables initialized with a literal or `constexpr`). Though it is not
specified in the standard this phase can be completed at compile time and saved in the data partition of the
executable.
Dynamic initialization all object initialization that is done via a constructor or function call (unless the function
is marked constexpr C++11). The dynamic initialization order is defined as the order of declaration within the
compilation unit (ie the same file). No guarantees about the order of initialization between compilation units is
provided.
Static members of a class. These are no different from file scope static variables in terms of lifespan (The major
difference is there viability).
Thread storage duration objects
Variables of this type are very similar to Static Storage duration objects. The main difference is the creation time is
just prior to thread creation and destruction is done after the thread has been joined.[8]
Automatic storage duration objects
These are the most common type of variable in C++:[9]
local variables inside a function/block.
temporary variables.
The common feature about automatic variables is that they have a lifespan that is limited to the scope of the variable.
They are created and potentially initialized at the point of declaration (see below for details) and destroyed in the
reverse order of creation when the scope is left.
Local variables are created as the point of execution passes there declaration point. If the variable has a constructor
or initializer this is used to define the initial state of the object. Local variables are destroyed when the local block or
function that they are declared in is closed.
Member variables are created when the parent object is created. Array members are initialized from 0 to the last
member of the array in order. Member variables are destroyed when the parent object is destroyed in the reverse
order of creation. i.e. If the parent is an "automatic object" then it will be destroyed when it goes out of scope which
triggers the destruction of all its members.
Temporary variables are created as the result of expression evaluation and are destroyed when the statement
containing the expression has been fully evaluated (usually at the ';' at the end of the statement).
C++
6
Dynamic storage duration objects
These objects have a dynamic lifespan and are created with new call and destroyed with an explicit call to delete.[10]
Templates
See also: Template metaprogramming and Generic programming
C++ templates enable generic programming. C++ supports both function and class templates. Templates may be
parameterized by types, compile-time constants, and other templates. 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 error" (SFINAE). Templates are a
powerful tool that can be used for generic programming, template metaprogramming, and code optimization, but this
power implies a cost. Template use may increase code size, because each template instantiation produces a copy of
the template code: one for each set of template arguments, however, this is the same amount of code that would be
generated, or less, that if the code was written by hand. This is in contrast to run-time generics seen in other
languages (e.g., Java) 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 polymorphism (see
below) and generic programming.
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 metaprogram 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
Main article: C++ classes
C++ introduces object-oriented programming (OOP) features to C. It offers classes, which provide the four features
commonly present in OOP (and some non-OOP) languages: abstraction, encapsulation, inheritance, and
polymorphism. One distinguishing feature of C++ classes compared to classes in other programming languages is
support for deterministic destructors, which in turn provide support for the Resource Acquisition is Initialization
(RAII) concept.
C++
7
Encapsulation
Encapsulation is the hiding of information 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 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 programming.
It is generally considered good practice to make all data 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
Inheritance 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 inheritance. 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 inheritance is a C++ feature not found in most other languages, allowing a class to be derived from more
than one base class; 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 Java, accomplish something
similar (although more limited) by allowing inheritance of multiple interfaces 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
See also: Polymorphism in object-oriented programming
Polymorphism 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.
C++
8
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 parameters. 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 Pattern, it's possible to implement a form of static polymorphism that closely
mimics the syntax for overriding virtual functions. Because 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 metaprogramming. Contrary to some opinion, template code will not generate a bulk code after compilation
with the proper compiler settings.
Dynamic polymorphism
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 information (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 has no runtime overhead and
does not require RTTI.
Virtual member functions
Ordinarily, when a function in a derived class overrides 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 dispatch. 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 name 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.
C++
9
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.
Exception handling
Exception handling is a mechanism in C++ that is used to handle errors in a uniform manner and separately from the
main body of a programme's source code. Should an error occur, an exception is thrown (raised), which is then
caught by an exception handler. The code that might cause an exception to be thrown goes in a try block (is
enclosed in try { and }) and the exceptions are handled in separate catch blocks.
#include<iostream>
#include<vector>
int main()
try {
std::vector<int> vec{3,4,3,1};
int i{vec.at(4)};
}
//An exception handler, catches std::out_of_range
catch(std::out_of_range& e) {
std::cerr<<"Accessing a non-existent element: "<<e.what()<<'\n';
}
catch(std::exception& e) {
std::cerr<<"Exception thrown: "<<e.what()<<'\n';
}
Unknown exceptions from unknown errors can be caught by the handlers using catch(...) to catch all
exceptions. As all the standard library exceptions have std::exception as their base class, catching
std::exception will catch all standard library exceptions. As is shown above (e.what()), all exceptions that
derive from std::exception have a what() function that provides information about what caused the error std::out_of_range is a descendent of std::exception.
Standard library
The C++ standard consists of two parts: the core language and the C++ Standard Library; which C++ programmers
expect on every 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), smart pointers for automatic memory management, regular
expression support, multi-threading library, atomics support (allowing a variable to be read or written to be at most
one thread at a time without any external synchronisation), time utilities (measurement, getting current time, etc.), a
system for converting error reporting that doesn't use C++ exceptions into C++ exceptions, a random number
generator and a slightly modified version of the C standard library (to make it comply with the C++ type system).
A large part of the C++ library is based on the STL. This provides useful tools as containers (for example vectors
and lists), iterators to provide these containers with array-like access and algorithms to perform operations such as
searching and sorting. Furthermore (multi)maps (associative arrays) and (multi)sets are provided, all of which export
C++
10
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 features of the library are accessed by using the
#include directive to include a standard header. C++ provides 105 standard headers, of which 27 are deprecated.
The standard incorporates the STL was originally designed by Alexander Stepanov, who experimented with generic
algorithms and containers for many years. When he started with C++, he finally found a language where it was
possible to create generic algorithms (e.g., STL sort) that perform even better than, for example, the C standard
library qsort, thanks to C++ features like using inlining and compile-time binding instead of function pointers. The
standard does not refer to it as "STL", as it is merely a part of the standard library, but the term is still widely used to
distinguish it from the rest of the standard library (input/output streams, internationalization, diagnostics, the C
library subset, etc.).
Most C++ compilers, and all major ones, provide a standards conforming implementation of the C++ standard
library.
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 specialization. Recent
releases of most popular C++ compilers support almost all of the C++ 1998 standard.
To give compiler vendors greater freedom, the C++ standards committee decided not to dictate the implementation
of name mangling, exception handling, and other implementation-specific features. The downside of this decision is
that object code produced by different compilers is expected to be incompatible. There were, however, attempts to
standardize compilers for particular machines or operating systems (for example C++ ABI), though they seem to be
largely abandoned now.
With C
For more details on this topic, see Compatibility of C and C++.
C++ is often considered to be a superset of C, 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++. For example, C allows implicit conversion from void* to other pointer types, but C++ does not (for type
safety reasons). Also, C++ defines many new keywords, such as new and class, which may be used as identifiers
(for example, variable names) in a C program.
Some incompatibilities have been removed by the 1999 revision of the C standard (C99), which now supports C++
features such as line comments (//), and declarations mixed with code. On the other hand, C99 introduced a number
of new features that C++ did not support, were incompatible or redundant in C++, such as variable-length arrays,
native complex-number types (use std::complex class that is, and was also there before C99 existed, in the C++
standard library), designated initializers (use constructors instead), compound literals, the boolean typedef (in C++ it
is a fundamental type) and the restrict keyword. Some of the C99-introduced features were included in the
subsequent version of the C++ standard, C++11 (out of those which were not redundant).
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).
C++
11
References
[1]
[2]
[3]
[4]
[5]
[6]
Further reading
Abrahams, David; Gurtovoy, Aleksey. C++ Template Metaprogramming: Concepts, Tools, and Techniques from
Boost and Beyond. Addison-Wesley. ISBN0-321-22725-5.
Alexandrescu, Andrei (2001). Modern C++ Design: Generic Programming and Design Patterns Applied.
Addison-Wesley. ISBN0-201-70431-5.
Alexandrescu, Andrei; Sutter, Herb (2004). C++ Design and Coding Standards: Rules and Guidelines for
Writing Programs. Addison-Wesley. ISBN0-321-11358-6.
Becker, Pete (2006). The C++ Standard Library Extensions : A Tutorial and Reference. Addison-Wesley.
ISBN0-321-41299-0.
Brokken, Frank (2010). C++ Annotations (http://www.icce.rug.nl/documents/cplusplus/). University of
Groningen. ISBN90-367-0470-7.
Coplien, James O. (1992, reprinted with corrections 1994). Advanced C++: Programming Styles and Idioms.
ISBN0-201-54855-0.
Dewhurst, Stephen C. (2005). C++ Common Knowledge: Essential Intermediate Programming. Addison-Wesley.
ISBN0-321-32192-8.
Information Technology Industry Council (15 October 2003). Programming languages C++ (Second ed.).
Geneva: ISO/IEC. 14882:2003(E).
Josuttis, Nicolai M. (2012). The C++ Standard Library, A Tutorial and Reference (Second ed.). Addison-Wesley.
ISBN0-321-62321-5.
Koenig, Andrew; Moo, Barbara E. (2000). Accelerated C++ Practical Programming by Example.
Addison-Wesley. ISBN0-201-70353-X.
Lippman, Stanley B.; Lajoie, Jose; Moo, Barbara E. (2011). C++ Primer (Fifth ed.). Addison-Wesley.
ISBN0-470-93244-9.
Lippman, Stanley B. (1996). Inside the C++ Object Model. Addison-Wesley. ISBN0-201-83454-5.
Meyers, Scott (2005). Effective C++ (Third ed.). Addison-Wesley. ISBN0-321-33487-6.
Stroustrup, Bjarne (2000). The C++ Programming Language (Special ed.). Addison-Wesley.
ISBN0-201-70073-5.
Stroustrup, Bjarne (1994). The Design and Evolution of C++. Addison-Wesley. ISBN0-201-54330-3.
C++
12
Stroustrup, Bjarne (2009). Programming Principles and Practice Using C++. Addison-Wesley.
ISBN0-321-54372-6.
Sutter, Herb (2001). More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and
Solutions. Addison-Wesley. ISBN0-201-70434-X.
Sutter, Herb (2004). Exceptional C++ Style. Addison-Wesley. ISBN0-201-76042-8.
Vandevoorde, David; Josuttis, Nicolai M. (2003). C++ Templates: The complete Guide. Addison-Wesley.
ISBN0-201-73484-2.
External links
Wikibooks has a book on the topic of: More C++ Idioms
Katdare, Kaustubh (1 February 2008). "Dr. Bjarne Stroustrup Inventor of C++" (http://www.crazyengineers.
com/threads/dr-bjarne-stroustrup-inventor-of-c.62739/). CrazyEngineers.
Code practices for not breaking binary compatibility between releases of C++ libraries (http://techbase.kde.org/
Policies/Binary_Compatibility_Issues_With_C++) (from KDE Techbase)
The Standard C++ Foundation (http://isocpp.org/) is a non-profit organization that promotes the use and
understanding of standard C++. Bjarne Stroustrup is a director of the organization.
13
C++ Standard
Library
Input/output
Strings
Standard Template Library
algorithm
functional
iterator
Sequence containers
Associative containers
14
Data types
Character classification
Strings
Mathematics
File input/output
Date/time
Localization
Memory allocation
Process control
Signals
Alternative tokens
Miscellaneous headers:
<assert.h>
<errno.h>
<setjmp.h>
<stdarg.h>
v
t
e [5]
Standard headers
The following files contain the declarations of the C++ Standard Library.
Containers
<array>
New in C++11 and TR1. Provides the container class template std::array, a container for a fixed sized
array.
<bitset>
Provides the specialized container class std::bitset, a bit array.
<deque>
Provides the container class template std::deque, a double-ended queue.
<forward_list>
New in C++11 and TR1. Provides the container class template std::forward_list, a singly linked list.
<list>
Provides the container class template std::list, a doubly linked list.
<map>
Provides the container class templates std::map and std::multimap, sorted associative array and
multimap.
<queue>
Provides the container adapter class std::queue, a single-ended queue, and std::priority_queue, a
priority queue.
<set>
Provides the container class templates std::set and std::multiset, sorted associative containers or
sets.
<stack>
15
and
<unordered_set>
New in C++11 and TR1. Provides the container class template std::unordered_set
std::unordered_multiset.
and
<vector>
Provides the container class template std::vector, a dynamic array.
General
<algorithm>
Provides definitions of many container algorithms.
<chrono>
Provides time elements, such as std::chrono::duration, std::chrono::time_point, and
clocks.
<functional>
Provides several function objects, designed for use with the standard algorithms.
<iterator>
Provides classes and templates for working with iterators.
<memory>
Provides facilities for memory management in C++, including the class template std::unique_ptr.
<stdexcept>
Contains standard exception classes such as std::logic_error and std::runtime_error, both
derived from std::exception.
<tuple>
New in C++11 and TR1. Provides a class template std::tuple, a tuple.
<utility>
Provides the template class std::pair, for working with object pairs (two-member tuples), and the
namespace std::rel_ops, for easier operator overloading.
Localization
<locale>
Defines classes and declares functions that encapsulate and manipulate the information peculiar to a locale.
<codecvt>
Provides code conversion facets for various character encodings.
Strings
<string>
Provides the C++ standard string classes and templates.
<regex>
Language support
<exception>
Provides several types and functions related to exception handling, including std::exception, the base
class of all exceptions thrown by the Standard Library.
<limits>
Provides the template class std::numeric_limits, used for describing properties of fundamental
numeric types.
<new>
Provides operators new and delete and other functions and types composing the fundamentals of C++
memory management.
<typeinfo>
Provides facilities for working with C++ run-time type information.
16
Numerics library
Components that C++ programs may use to perform seminumerical operations.
<complex>
The header <complex> defines a class template, and numerous functions for representing and manipulating
complex numbers.
<random>
Facility for generating (pseudo-)random numbers
<valarray>
Defines five class templates (valarray, slice_array, gslice_array, mask_array, and indirect_array), two classes
(slice and gslice), and a series of related function templates for representing and manipulating arrays of values.
<numeric>
Generalized numeric operations.
C standard library
Main article: C Standard Library
Each header from the C Standard Library is included in the C++ Standard Library under a different name, generated
by removing the .h, and adding a 'c' at the start; for example, 'time.h' becomes 'ctime'. The only difference between
these headers and the traditional C Standard Library headers is that where possible the functions should be placed
into the std:: namespace. In ISO C, functions in the standard library are allowed to be implemented by macros, which
is not allowed by ISO C++.
17
18
References
[1]
[2]
[3]
[4]
[5]
External links
Standard C++ Library reference (http://en.cppreference.com/w/cpp)
Microsoft MSDN Library - Standard C++ Library Reference (http://msdn2.microsoft.com/en-us/library/
cscc687y(VS.80).aspx)
SourcePro C++ Documentation (http://www.roguewave.com/support/product-documentation/sourcepro.
aspx)
STLport (http://www.stlport.org/)
The GNU Standard C++ Library (http://gcc.gnu.org/libstdc++)
Input/output
Strings
Standard Template Library
algorithm
functional
iterator
Sequence containers
Associative containers
Data types
Character classification
Strings
Mathematics
File input/output
Date/time
Localization
Memory allocation
Process control
Signals
Alternative tokens
Miscellaneous headers:
<assert.h>
<errno.h>
<setjmp.h>
<stdarg.h>
19
v
t
e [5]
The Standard Template Library (STL) is a software library for the C++ programming language that influenced
many parts of the C++ Standard Library. It provides four components called algorithms, containers, functional, and
iterators.
The STL provides a ready-made set of common classes for C++, such as containers and associative arrays, that can
be used with any built-in type and with any user-defined type that supports some elementary operations (such as
copying and assignment). STL algorithms are independent of containers, which significantly reduces the complexity
of the library.
The STL achieves its results through the use of templates. This approach provides compile-time polymorphism that
is often more efficient than traditional run-time polymorphism. Modern C++ compilers are tuned to minimize any
abstraction penalty arising from heavy use of the STL.
The STL was created as the first library of generic algorithms and data structures for C++, with four ideas in mind:
generic programming, abstractness without loss of efficiency, the Von Neumann computation model, and value
semantics.
Composition
Containers
The STL contains sequence containers and associative containers. The standard sequence containers include
vector , deque , and list . The standard associative containers are set , multiset , map , and
multimap . There are also container adaptorsqueue , priority_queue , and stack , that are containers
with specific interface, using other containers as implementation.
Container
Description
Simple Containers
pair
The pair container is a simple associative container consisting of a 2-tuple of data elements or objects, called 'first' and
'second', in that fixed order. The STL 'pair' can be assigned, copied and compared. The array of objects allocated in a map
or hash_map (described below) are of type 'pair' by default, where all the 'first' elements act as the unique keys, each
associated with their 'second' value objects.
Sequences (Arrays/Linked Lists): ordered collections
vector
a dynamic array, like C array (i.e., capable of random access) with the ability to resize itself automatically when inserting
or erasing an object. Inserting and removing an element to/from back of the vector at the end takes amortized constant
time. Inserting and erasing at the beginning or in the middle is linear in time. A specialization for type bool exists, which
optimizes for space by storing bool values as bits.
list
a doubly linked list; elements are not stored in contiguous memory. Opposite performance from a vector. Slow lookup
and access (linear time), but once a position has been found, quick insertion and deletion (constant time).
deque (double-ended
queue)
a vector with insertion/erase at the beginning or end in amortized constant time, however lacking some guarantees on
iterator validity after altering the deque.
Container adaptors
queue
Provides FIFO queue interface in terms of push /pop /front /back operations. Any sequence supporting
operations front() , back() , push_back() , and pop_front() can be used to instantiate
queue (e.g. list and deque ).
priority queue
20
Provides priority queue interface in terms of push/pop/top operations (the element with the highest priority is
on top). Any random-access sequence supporting operations front() , push_back() , and
pop_back() can be used to instantiate priority_queue (e.g. vector and deque ).
Elements should additionally support comparison (to determine which element has a higher priority and should be popped
first).
stack
Provides LIFO stack interface in terms of push/pop/top operations (the last-inserted element is on top). Any
sequence supporting operations back() , push_back() , and pop_back() can be used to instantiate
stack (e.g. vector , list , and deque ).
Associative containers: unordered collections
set
multiset
map
multimap
unordered_set
unordered_multiset
unordered_map
unordered_multimap
a mathematical set; inserting/erasing elements in a set does not invalidate iterators pointing in the set. Provides set
operations union, intersection, difference, symmetric difference and test of inclusion. Type of data must implement
comparison operator < or custom comparator function must be specified; such comparison operator or comparator
function must guarantee strict weak ordering, otherwise behavior is undefined. Typically implemented using a
self-balancing binary search tree.
same as a set, but allows duplicate elements (mathematical Multiset).
an associative array; allows mapping from one data item (a key) to another (a value). Type of key must implement
comparison operator < or custom comparator function must be specified; such comparison operator or comparator
function must guarantee strict weak ordering, otherwise behavior is undefined. Typically implemented using a
self-balancing binary search tree.
same as a map, but allows duplicate keys.
similar to a set, multiset, map, or multimap, respectively, but implemented using a hash table; keys are not ordered, but a
hash function must exist for the key type. These containers are part of C++11.
valarray
stores series of bits similar to a fixed-sized vector of bools. Implements bitwise operations and lacks iterators. Not a
Sequence.
another C-like array like vector, but is designed for high speed numerics at the expense of some programming ease and
general purpose use. It has many features that make it ideally suited for use with vector processors in traditional vector
supercomputers and SIMD units in consumer-level scalar processors, and also ease vector mathematics programming
even in scalar computers.
Iterators
The STL implements five different types of iterators. These are input iterators (that can only be used to read a
sequence of values), output iterators (that can only be used to write a sequence of values), forward iterators (that can
be read, written to, and move forward), bidirectional iterators (that are like forward iterators, but can also move
backwards) and random access iterators (that can move freely any number of steps in one operation).
It is possible to have bidirectional iterators act like random access iterators, as moving forward ten steps could be
done by simply moving forward a step at a time a total of ten times. However, having distinct random access
iterators offers efficiency advantages. For example, a vector would have a random access iterator, but a list only a
bidirectional iterator.
Iterators are the major feature that allow the generality of the STL. For example, an algorithm to reverse a sequence
can be implemented using bidirectional iterators, and then the same implementation can be used on lists, vectors and
deques. User-created containers only have to provide an iterator that implements one of the five standard iterator
interfaces, and all the algorithms provided in the STL can be used on the container.
This generality also comes at a price at times. For example, performing a search on an associative container such as a
map or set can be much slower using iterators than by calling member functions offered by the container itself. This
is because an associative container's methods can take advantage of knowledge of the internal structure, which is
Algorithms
A large number of algorithms to perform operations such as searching and sorting are provided in the STL, each
implemented to require a certain level of iterator (and therefore will work on any container that provides an interface
by iterators).
Functors
The STL includes classes that overload the function call operator (operator() ). Instances of such classes are
called functors or function objects. Functors allow the behavior of the associated function to be parameterized (e.g.
through arguments passed to the functor's constructor) and can be used to keep associated per-functor state
information along with the function. Since both functors and function pointers can be invoked using the syntax of a
function call, they are interchangeable as arguments to templates when the corresponding parameter only appears in
function call contexts.
A particularly common type of functor is the predicate. For example, algorithms like find_if take a unary
predicate that operates on the elements of a sequence. Algorithms like sort, partial_sort, nth_element and all sorted
containers use a binary predicate that must provide a strict weak ordering, that is, it must behave like a membership
test on a transitive, non reflexive and asymmetric binary relation. If none is supplied, these algorithms and containers
use less [1] by default, which in turn calls the less-than-operator <.
History
The architecture of STL is largely the creation of Alexander Stepanov. In 1979 he began working out his initial ideas
of generic programming and exploring their potential for revolutionizing software development. Although David
Musser had developed and advocated some aspects of generic programming already by year 1971, it was limited to a
rather specialized area of software development (computer algebra).
Stepanov recognized the full potential for generic programming and persuaded his then-colleagues at General
Electric Research and Development (including, primarily, David Musser and Deepak Kapur) that generic
programming should be pursued as a comprehensive basis for software development. At the time there was no real
support in any programming language for generic programming.
The first major language to provide such support was Ada (ANSI standard 1983), with its generic units feature. In
1985, the Eiffel programming language became the first object-oriented language to include intrinsic support for
generic classes, combined with the object-oriented notion of inheritance.[2] By 1987 Stepanov and Musser had
developed and published an Ada library for list processing that embodied the results of much of their research on
generic programming. However, Ada had not achieved much acceptance outside the defense industry and C++
seemed more likely to become widely used and provide good support for generic programming even though the
language was relatively immature. Another reason for turning to C++, which Stepanov recognized early on, was the
C/C++ model of computation that allows very flexible access to storage via pointers, which is crucial to achieving
generality without losing efficiency.
Much research and experimentation were needed, not just to develop individual components, but to develop an
overall architecture for a component library based on generic programming. First at AT&T Bell Laboratories and
later at Hewlett-Packard Research Labs (HP), Stepanov experimented with many architectural and algorithm
formulations, first in C and later in C++. Musser collaborated in this research and in 1992 Meng Lee joined
Stepanov's project at HP and became a major contributor.
This work undoubtedly would have continued for some time being just a research project or at best would have
resulted in an HP proprietary library, if Andrew Koenig of Bell Labs had not become aware of the work and asked
21
Criticisms
Quality of implementation of C++ compilers
The Quality of Implementation (QoI) of the C++ compiler has a large impact on usability of STL (and templated
code in general):
Error messages involving templates tend to be very long and difficult to decipher. This problem has been
considered so severe that a number of tools have been written that simplify and prettyprint STL-related error
messages to make them more comprehensible.
Careless use of STL templates can lead to code bloat.Wikipedia:Citation needed This has been countered with
special techniques within STL implementation (using void* containers internally) and by improving optimization
techniques used by compilers. This is similar to carelessly just copying a whole set of C library functions to work
with a different type.
Template instantiation tends to increase compilation time and memory usage (even by an order of
magnitude)Wikipedia:Citation needed. Until the compiler technology improves enough, this problem can be only
partially eliminated by very careful coding and avoiding certain idioms.
22
Other issues
Initialization of STL containers with constants within the source code is not as easy as data structures inherited
from C (addressed in C++11 with initializer lists).
STL containers are not intended to be used as base classes (their destructors are deliberately non-virtual); deriving
from a container is a common mistake.
The concept of iterators as implemented by STL can be difficult to understand at first: for example, if a value
pointed to by the iterator is deleted, the iterator itself is then no longer valid. This is a common source of errors.
Most implementations of the STL provide a debug mode that is slower, but can locate such errors if used. A
similar problem exists in other languages, for example Java. Ranges have been proposed as a safer, more flexible
alternative to iterators.
Certain iteration patterns do not map to the STL iterator model.Wikipedia:Citation needed For example, callback
enumeration APIs cannot be made to fit the STL model without the use of coroutines, which are
platform-dependent or unavailable, and are outside the C++ standard.
Compiler compliance does not guarantee that Allocator objects, used for memory management for containers, will
work with state-dependent behavior. For example, a portable library can't define an allocator type that will pull
memory from different pools using different allocator objects of that type. (Meyers, p.50) (addressed in C++11).
The set of algorithms is not complete: for example, the copy_if algorithm was left out, though it has been
added in C++11.[3]
The interface of some containers (in particular string) is argued to be bloated (Sutter and Alexandrescu, p.79);
others are argued to be insufficient.
Hashing containers were left out of the original standard (but added in Technical Report 1 for C++03), and have
been added in C++11.
Implementations
Original STL implementation by Stepanov and Lee. 1994, Hewlett-Packard. No longer maintained.
SGI STL, based on original implementation by Stepanov & Lee. 1997, Silicon Graphics. No longer maintained.
libstdc++ by the GNU Project (was part of libg++)
libc++ from clang
STLPort, based on SGI STL
Rogue Wave Standard Library (HP, SGI, SunSoft, Siemens-Nixdorf)
Dinkum STL library by P.J. Plauger
The Microsoft STL [4] which ships with Visual C++ is a licensed derivative of Dinkum's STL.
Apache C++ Standard Library [5] (The starting point for this library was the 2005 version of the Rogue Wave
standard library[6])
EASTL [7], developed by Paul Pedriana at Electronic Arts and published as part of EA Open Source [8].
23
Notes
[1] http:/ / www. sgi. com/ tech/ stl/ less. html
[2] Meyer, Bertrand. Genericity versus inheritance, in ACM Conference on Object-Oriented Programming Languages Systems and Applications
(OOPSLA), Portland (Oregon), September 29 - October 2, 1986, pages 391-405.
[3] More STL algorithms (revision 2) (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2008/ n2666. pdf)
[4] http:/ / msdn. microsoft. com/ en-us/ library/ c191tb28(v=vs. 80). aspx
[5] http:/ / stdcxx. apache. org
[6] Apache C++ Standard Library (http:/ / stdcxx. apache. org/ ). Stdcxx.apache.org. Retrieved on 2013-07-29.
[7] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2007/ n2271. html
[8] http:/ / gpl. ea. com/
References
Alexander Stepanov and Meng Lee, The Standard Template Library. HP Laboratories Technical Report
95-11(R.1), 14 November 1995. (Revised version of A. A. Stepanov and M. Lee: The Standard Template Library,
Technical Report X3J16/94-0095, WG21/N0482, ISO Programming Language C++ Project, May 1994.) (http://
www.stepanovpapers.com)
Alexander Stepanov (2007). Notes on Programming (http://www.stepanovpapers.com/notes.pdf) (PDF).
Stepanov reflects about the design of the STL.
Nicolai M. Josuttis (2000). The C++ Standard Library: A Tutorial and Reference. Addison-Wesley.
ISBN0-201-37926-0.
Scott Meyers (2001). Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library.
Addison-Wesley. ISBN0-201-74962-9.
Al Stevens (March 1995). "Al Stevens Interviews Alex Stepanov" (http://www.sgi.com/tech/stl/
drdobbs-interview.html). Dr. Dobb's Journal. Retrieved 18 July 2007.
David Vandevoorde and Nicolai M. Josuttis (2002). C++ Templates: The Complete Guide. Addison-Wesley
Professional. ISBN0-201-73484-2.
Atul Saini and David R. Musser, STL Tutorial and Reference Guide: C+ + Programming with the Standard
Template Library. Foreword by Alexander Stepanov; [Copyright Modena Software Inc.] Addison-Wesley ISBN
0-201-63398-1
External links
C/C++ STL reference (http://en.cppreference.com/w/cpp/container), includes C++11 features
STL programmer's guide (http://www.sgi.com/tech/stl/) guide from SGI
Apache (formerly Rogue Wave) C++ Standard Library Class Reference (http://stdcxx.apache.org/doc/
stdlibref/index.html)
Apache (formerly Rogue Wave) C++ Standard Library User Guide (http://stdcxx.apache.org/doc/stdlibug/
index.html)
Bjarne Stroustrup on The emergence of the STL (http://www.stroustrup.com/DnE2005.pdf) (Page 5, Section
3.1)
24
25
[1]
, then
Overview
Compilers needed not include the TR1 components to be conforming to the C++ standard, because TR1 proposals
were not part of the standard itself, but only a set of possible additions that were still to be ratified. However, most of
it was available from Boost, and several compiler/library distributors implemented all or part of the components.
TR1 was not a complete list of additions to the library that were going to appear in the next standard, C++11. For
example, C++11 includes thread support library that is not available in TR1.
The new components were defined in the std::tr1 namespace to distinguish them from the then current standard
library.
There is also a second technical report, C++ Technical Report 2, planned for publishing after C++11 [3].
Components
TR1 includes the following components:
General utilities
Reference wrapper enables passing references, rather than copies, into algorithms or function objects. The feature
was based on Boost.Ref.[4] A wrapper reference is obtained from an instance of the template class
reference_wrapper. Wrapper references are similar to normal references (&) of the C++ language. To obtain
a wrapper reference from any object the template class ref is used (for a constant reference cref is used).
Wrapper references are useful above all for template functions, when argument deduction would not deduce a
reference (e.g. when forwarding arguments):
#include <iostream>
#include <tr1/functional>
{ ++r; }
int main()
{
26
int i = 0;
g( f, i );
// Output: 0
g( f, std::tr1::ref(i) );
// Output: 1
Smart pointers adds several classes that simplify object lifetime management in complex cases. Three main
classes are added:
shared_ptr a reference-counted smart pointer
weak_ptr a variant of shared_ptr that doesn't increase the reference count
The proposal is based on Boost Smart Pointer library [5]
Function objects
These four modules are added to the <functional> header file:
Polymorphic function wrapper (function) can store any callable function (function pointers, member
function pointers, and function objects) that uses a specified function call signature. The type does not depend on the
kind of the callable used. Based on Boost.Function [6]
Function object binders (bind) can bind any parameter parameters to function objects. Function composition is
also allowed. This is a generalized version of the standard std::bind1st and std::bind2nd bind functions.
The feature is based on Boost Bind library.[7]
Function return types (result_of) determines the type of a call expression.
mem_fn enhancement to the standard std::mem_fun and std::mem_fun_ref. Allows pointers to member
functions to be treated as function objects. Based on Boost Mem Fn library [8]
Numerical facilities
Random number generation
new <random> header file variate_generator, mersenne_twister, poisson_distribution,
etc.
utilities for generating random numbers using any of several Pseudorandom number generators, engines, and
probability distributions
27
Function
prototype
Associated
Laguerre
polynomials
double
assoc_laguerre(
unsigned n,
unsigned m,
double x ) ;
Associated
Legendre
polynomials
double
assoc_legendre(
unsigned l,
unsigned m,
double x ) ;
Beta function
double beta(
double x, double y
);
double
comp_ellint_2(
double k ) ;
Complete elliptic
integral of the
third kind
double
comp_ellint_3(
double k, double
nu ) ;
Confluent
hypergeometric
functions
double
conf_hyperg(
double a, double c,
double x ) ;
Regular modified
cylindrical Bessel
functions
double
cyl_bessel_i(
double nu, double
x);
Cylindrical Bessel
functions of the
first kind
double
cyl_bessel_j(
double nu, double
x);
Mathematical expression
Cylindrical
Neumann functions
Cylindrical Bessel
functions of the
second kind
double
cyl_neumann(
double nu, double
x);
double expint(
double x ) ;
Hermite
polynomials
double hermite(
unsigned n, double
x);
Hypergeometric
series
double hyperg(
double a, double b,
double c, double x
);
Laguerre
polynomials
double laguerre(
unsigned n, double
x);
Legendre
polynomials
double legendre(
unsigned l, double
x);
Riemann zeta
function
Spherical Bessel
functions of the
first kind
double
riemann_zeta(
double x ) ;
double
sph_bessel(
unsigned n, double
x);
Spherical
double
associated
sph_legendre(
Legendre functions unsigned l,
unsigned m,
double theta ) ;
Spherical
Neumann functions
Spherical Bessel
functions of the
second kind
double
sph_neumann(
unsigned n, double
x);
Each function has two additional variants. Appending the suffix f or l to a function name gives a function that
operates on float or long double values respectively. For example:
28
Containers
Tuple types
Regular expressions
new <regex> header file regex, regex_match, regex_search, regex_replace, etc.
based on Boost RegEx library [12]
pattern matching library
C compatibility
C++ is designed to be compatible with the C programming language, but is not a strict superset of C due to diverging
standards. TR1 attempts to reconcile some of these differences through additions to various headers in the C++
library, such as <complex>, <locale>, <cmath>, etc. These changes help to bring C++ more in line with the C99
version of the C standard (not all parts of C99 are included in TR1).
29
Technical Report 2
In 2005 a request for proposals for a TR2 was made with a special interest in Unicode, XML/HTML, Networking
and usability for novice programmers.[3].
Some of the proposals included:
Threads [13]
The Asio C++ library (networking [14][15]).
Signals/Slots [16][17]
Filesystem Library [18] Based on the Boost Filesystem Library, for query/manipulation of paths, files and
directories.
Boost Any Library [19]
Lexical Conversion Library [20]
New String Algorithms [21]
Toward a More Complete Taxonomy of Algebraic Properties for Numeric Libraries in TR2 [22]
Adding heterogeneous comparison lookup to associative containers for TR2 [23]
Since the call for proposals for TR2 changes to ISO procedures meant that there will not be a TR2, instead
enhancements to C++ will be published in a number of Technical Specifications. Some of the proposals listed above
are already included in the C++ standard or in draft versions of the Technical Specifications.
Notes
[1] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1836. pdf
[2] http:/ / www. iso. org/ iso/ iso_catalogue/ catalogue_ics/ catalogue_detail_ics. htm?ics1=35& ics2=60& ics3=& csnumber=43289
[3] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1810. html
[4] Chapter 22. Boost.Ref Boost 1.48.0 (http:/ / www. boost. org/ doc/ html/ ref. html)
[5] Smart Pointers Boost 1.48.0 (http:/ / www. boost. org/ libs/ smart_ptr/ smart_ptr. htm)
[6] Chapter 9. Boost.Function Boost 1.48.0 (http:/ / www. boost. org/ doc/ html/ function. html)
[7] Boost: bind.hpp documentation Boost 1.48.0 (http:/ / www. boost. org/ libs/ bind/ bind. html)
[8] Boost: mem_fn.hpp documentation Boost 1.48.0 (http:/ / www. boost. org/ libs/ bind/ mem_fn. html)
[9] http:/ / www. boost. org/ doc/ libs/ 1_37_0/ libs/ type_traits/ doc/ html/ index. html
[10] The Boost Tuple Library Boost 1.48.0 (http:/ / www. boost. org/ libs/ tuple/ doc/ tuple_users_guide. html)
[11] Chapter 3. Boost.Array Boost 1.48.0 (http:/ / www. boost. org/ doc/ html/ array. html)
[12] Boost.Regex Boost 1.36.0 (http:/ / www. boost. org/ doc/ libs/ 1_36_0/ libs/ regex/ doc/ html/ index. html)
[13] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1883. pdf
[14] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1925. pdf
[15] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2007/ n2175. pdf
[16] http:/ / www. mail-archive. com/ libsigc-list@gnome. org/ msg00115. html
[17] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2006/ n2086. pdf
[18] http:/ / www. open-std. org/ JTC1/ sc22/ WG21/ docs/ papers/ 2011/ n3239. html
[19] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2006/ n1939. html
[20] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2006/ n1973. html
[21] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2006/ n2059. html#abstract
[22] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2008/
[23] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2009/ n2882. pdf
30
References
ISO/IEC JTC1/SC22/WG21 (2005-06-24). Draft Technical Report on C++ Library Extensions (http://www.
open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf) (PDF).
"ISO/IEC TR 19768:2007" (http://www.iso.org/iso/iso_catalogue/catalogue_ics/catalogue_detail_ics.
htm?ics1=35&ics2=60&ics3=&csnumber=43289).
Becker, Peter (2006). The C++ Standard Library Extensions: A Tutorial and Reference. Addison-Wesley
Professional. ISBN0-321-41299-0.
External links
Scott Meyers' Effective C++: TR1 Information (http://aristeia.com/EC3E/TR1_info_frames.html) contains
links to the TR1 proposal documents which provide background and rationale for the TR1 libraries.
31
32
Boost logo
Stable release
Written in
C++
Type
Libraries
License
Website
www.boost.org
[1]
Boost is a set of libraries for the C++ programming language that provide support for tasks and structures such as
linear algebra, pseudorandom number generation, multithreading, image processing, regular expressions, and unit
testing. It contains over eighty individual libraries.
Most of the Boost libraries are licensed under the Boost Software License, designed to allow Boost to be used with
both free and proprietary software projects. Many of Boost's founders are on the C++ standards committee, and
several Boost libraries have been accepted for incorporation into both Technical Report 1 and the C++11 standard.
Design
The libraries are aimed at a wide range of C++ users and application domains. They range from general-purpose
libraries like the smart pointer library, to operating system abstractions like Boost FileSystem, to libraries primarily
aimed at other library developers and advanced C++ users, like the template metaprogramming (MPL) and
domain-specific language (DSL) creation (Proto).
In order to ensure efficiency and flexibility, Boost makes extensive use of templates. Boost has been a source of
extensive work and research into generic programming and metaprogramming in C++.Wikipedia:Citation needed
Most Boost libraries are header based, consisting of inline functions and templates, and as such do not need to be
built in advance of their use. Some Boost libraries coexist as independent libraries.
33
Associated people
Original founders of Boost still active in the community include Beman Dawes and David Abrahams. Author of
several books on C++, Nicolai Josuttis contributed the Boost array library in 2001. There are mailing lists devoted to
Boost library use and library development, active as of 2014[2].
References
[1] http:/ / www. boost. org/
[2] http:/ / en. wikipedia. org/ w/ index. php?title=Boost_(C%2B%2B_libraries)& action=edit
Further reading
Demming, Robert & Duffy, Daniel J. (2010). Introduction to the Boost C++ Libraries. Volume 1 - Foundations.
Datasim. ISBN978-94-91028-01-4.
Demming, Robert & Duffy, Daniel J. (2012). Introduction to the Boost C++ Libraries. Volume 2 - Advanced
Libraries. Datasim. ISBN978-94-91028-02-1.
Karlsson, Bjrn (2005). Beyond the C++ Standard Library: An Introduction to Boost. Addison-Wesley.
ISBN978-0-321-13354-0.
Polukhin, Antony (2013). Boost C++ Application Development Cookbook. Packt. ISBN978-1-84951-488-0.
Schling, Boris (2011). The Boost C++ Libraries. XML Press. ISBN978-0-9822191-9-5.
Siek, Jeremy G.; Lee, Lie-Quan & Lumsdaine, Andrew (2001). The Boost Graph Library: User Guide and
Reference Manual. Addison-Wesley. ISBN978-0-201-72914-6.
External links
The Wikibook C++ Programming has a page on the topic of: Libraries/Boost
Const-correctness
34
Const-correctness
In computer programming, const-correctness is the form of program correctness that deals with the proper
declaration of variables or objects as mutable or immutable. The term is mostly used in a C or C++ context, and
takes its name from the const keyword in those languages.
The idea of const-ness does not imply that the variable as it is stored in the computer's memory is unwritable. Rather,
const-ness is a compile-time construct that indicates what a programmer should do, not necessarily what they can
do. Note, however, that in the case of predefined data (such as const char * string literals), C const is often
unwritable.
In addition, a (non-static) member-function can be declared as const. In this case, the this pointer inside such a
function is of type return_value_type const * const rather than merely of type
return_value_type * const. This means that non-const functions for this object cannot be called from
inside such a function, nor can member variables be modified. In C++, a member variable can be declared as
mutable, indicating that this restriction does not apply to it. In some cases, this can be useful, for example with
caching, reference counting, and data synchronization. In these cases, the logical meaning (state) of the object is
unchanged, but the object is not physically constant since its bitwise representation may change.
* ptr,
const * ptrToConst,
* const constPtr,
const * const constPtrToConst )
Const-correctness
{
*ptr = 0; // OK: modifies the "pointee" data
ptr = NULL; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the "pointee" data
ptrToConst = NULL; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the "pointee" data
constPtr = NULL; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the "pointee" data
constPtrToConst = NULL; // Error! Cannot modify the pointer
}
Following usual C convention for declarations, declaration follows use, and the * in a pointer is written on the
pointer, indicating dereferencing. For example, in the declaration int *ptr, the dereferenced form *ptr is an
int, while the reference form ptr is a pointer to an int. Thus const modifies the name to its right. The C++
convention is instead to associate the * with the type, as in int* ptr, and read the const as modifying the
type to the left. int const * ptrToConst can thus be read as "*ptrToConst is a int const" (the
value is constant), or "ptrToConst is a int const *" (the pointer is a pointer to a constant integer). Thus:
int *ptr; // *ptr is an int value
int const *ptrToConst; // *ptrToConst is a constant (int: integer
value)
int * const constPtr; // constPtr is a constant (int *: integer
pointer)
int const * const constPtrToConst; // constPtrToConst is a constant
(pointer)
// as is *constPtrToConst (value)
Following C++ convention of analyzing the type, not the value, a rule of thumb is to read the declaration from right
to left. Thus, everything to the left of the star can be identified as the pointee type and everything to the right of the
star are the pointer properties. For instance, in our example above, int const * can be read as a writable pointer
that refers to a non-writable integer, and int * const can be read as a non-writable pointer that refers to a
writable integer.
C/C++ also allows the const to be placed to the left of the type, in the following syntax:
const int*
ptrToConst;
//identical to: int const *
ptrToConst,
const int* const constPtrToConst;//identical to: int const * const
constPtrToConst
This more clearly separates the two locations for the const, and allows the * to always be bound to its preceding
type, though it still requires reading right-to-left, as follows:
int* ptr;
const int* ptrToConst; // (const int)*, not const (int*)
int* const constPtr;
const int* const constPtrToConst;
35
Const-correctness
Note, however, that despite the different convention for formatting C++ code, the semantics of pointer declaration
are the same:
int* a; // a is an int pointer
int* a, b; // TRICKY: a is an int pointer as above, but b is not; b is
an int value
int* a, *b; // both a and b are pointers; *a and *b are int values
Bjarne Stroustrup's FAQ recommends only declaring one variable per line if using the C++ convention, to avoid this
issue.[2]
C++ references follow similar rules. A declaration of a const reference is redundant since references can never be
made to refer to another object:
int i = 22;
int const & refToConst = i; // OK
int & const constRef = i; // Error the "const" is redundant
Even more complicated declarations can result when using multidimensional arrays and references (or pointers) to
pointers; however, someWikipedia:Manual of Style/Words to watch#Unsupported attributions have argued that these
are confusing and error-prone and that they therefore should generally be avoided or replaced with higher-level
structures.
Methods
In order to take advantage of the design by contract approach for user-defined types (structs and classes), which can
have methods as well as member data, the programmer must tag instance methods as const if they don't modify
the object's data members. Applying the const qualifier to instance methods thus is an essential feature for
const-correctness, and is not available in many other object-oriented languages such as Java and C# or in Microsoft's
C++/CLI or Managed Extensions for C++. While const methods can be called by const and non-const
objects alike, non-const methods can only be invoked by non-const objects. The const modifier on an instance
method applies to the object pointed to by the "this" pointer, which is an implicit argument passed to all instance
methods. Thus having const methods is a way to apply const-correctness to the implicit "this" pointer argument
just like other arguments.
This example illustrates:
class C
{
int i;
36
Const-correctness
public:
int Get() const // Note the "const" tag
{ return i; }
void Set(int j) // Note the lack of "const"
{ i = j; }
};
void Foo(C& nonConstC, const C& constC)
{
int y = nonConstC.Get(); // Ok
int x = constC.Get();
// Ok: Get() is const
nonConstC.Set(10); // Ok: nonConstC is modifiable
constC.Set(10);
// Error! Set() is a non-const method and constC
is a const-qualified object
}
In the above code, the implicit "this" pointer to Set() has the type "C *const"; whereas the "this" pointer
to Get() has type "const C *const", indicating that the method cannot modify its object through the "this"
pointer.
Often the programmer will supply both a const and a non-const method with the same name (but possibly quite
different uses) in a class to accommodate both types of callers. Consider:
class MyArray
{
int data[100];
public:
int &
Get(int i)
{ return data[i]; }
int const & Get(int i) const { return data[i]; }
};
void Foo( MyArray & array, MyArray const & constArray )
{
// Get a reference to an array element
// and modify its referenced value.
array.Get( 5 )
= 42; // OK! (Calls: int & MyArray::Get(int))
constArray.Get( 5 ) = 42; // Error! (Calls: int const &
MyArray::Get(int) const)
}
The const-ness of the calling object determines which version of MyArray::Get() will be invoked and thus
whether or not the caller is given a reference with which he can manipulate or only observe the private data in the
object. The two methods technically have different signatures because their "this" pointers have different types,
allowing the compiler to choose the right one. (Returning a const reference to an int, instead of merely returning
the int by value, may be overkill in the second method, but the same technique can be used for arbitrary types, as
in the Standard Template Library.)
37
Const-correctness
Loopholes to const-correctness
There are several loopholes to pure const-correctness in C and C++. They exist primarily for compatibility with
existing code.
The first, which applies only to C++, is the use of const_cast, which allows the programmer to strip the const
qualifier, making any object modifiable. The necessity of stripping the qualifier arises when using existing code and
libraries that cannot be modified but which are not const-correct. For instance, consider this code:
// Prototype for a function which we cannot change but which
// we know does not modify the pointee passed in.
void LibraryFunc(int *ptr, int size);
void CallLibraryFunc(int const *ptr, int size)
{
LibraryFunc(ptr, size); // Error! Drops const qualifier
int *nonConstPtr = const_cast<int*>(ptr); // Strip qualifier
LibraryFunc(nonConstPtr, size); // OK
}
However, any attempt to modify an object that is itself declared const by means of const_cast results in
undefined behavior according to the ISO C++ Standard. In the example above, if ptr references a global, local, or
member variable declared as const, or an object allocated on the heap via new const int, the code is only
correct if LibraryFunc really does not modify the value pointed to by ptr.
The C language has a need of a loophole because a certain situation exists. Variables with static storage duration are
allowed to be defined with an initial value. However, the initializer can use only constants like string constants and
other literals, and are not allowed to use non-constant elements like variable names, whether the initializer elements
are declared const or not, or whether the static duration variable is being declared const or not. There is a
non-portable way to initialize a const variable that has static storage duration. By carefully constructing a typecast
on the left hand side of a later assignment, a const variable can be written to, effectively stripping away the
const attribute and 'initializing' it with non-constant elements like other const variables and such. Writing into a
const variable this way may work as intended, but it causes undefined behavior and seriously contradicts
const-correctness:
const size_t
bufferSize = 8*1024;
const size_t
userTextBufferSize; //initial value depends on const
bufferSize, can't be initialized here
...
int setupUserTextBox(textBox_t *defaultTextBoxType, rect_t
*defaultTextBoxLocation)
{
*(size_t*)&userTextBufferSize = bufferSize - sizeof(struct
textBoxControls); // warning: might work, but not guaranteed by C
...
}
Another loopholeWikipedia:Citation needed applies both to C and C++. Specifically, the languages dictate that
member pointers and references are "shallow" with respect to the const-ness of their owners that is, a
38
Const-correctness
39
containing object that is const has all const members except that member pointees (and referees) are still
mutable. To illustrate, consider this code:
struct S
{
int val;
int *ptr;
};
void Foo(const S
{
int i = 42;
s.val = i;
s.ptr = &i;
*s.ptr = i;
& s)
}
Although the object s passed to Foo() is constant, which makes all of its members constant, the pointee
accessible through s.ptr is still modifiable, though this may not be desirable from the standpoint of
const-correctness because s might solely own the pointee. For this reason, someWikipedia:Manual of
Style/Words to watch#Unsupported attributions have argued that the default for member pointers and references
should be "deep" const-ness, which could be overridden by a mutable qualifier when the pointee is not owned
by the container, but this strategy would create compatibility issues with existing code. Thus, for historical
reasonsWikipedia:Citation needed, this loophole remains open in C and C++.
The latter loophole can be closed by using a class to hide the pointer behind a const-correct interface, but such
classes either don't support the usual copy semantics from a const object (implying that the containing class
cannot be copied by the usual semantics either) or allow other loopholes by permitting the stripping of const-ness
through inadvertent or intentional copying.
Finally, several functions in the C standard library violate const-correctness, as they accept a const pointer to a
character string and return a non-const pointer to a part of the same string. strtol and strchr are among
these functions. Some implementations of the C++ standard library, such as Microsoft's try to close this loophole by
providing two overloaded versions of some functions: a "const" version and a "non-const" version.
Volatile-correctness
The other qualifier in C and C++, volatile, indicates that an object may be changed by something external to the
program at any time and so must be re-read from memory every time it is accessed.
The qualifier is most often found in code that manipulates hardware directly (such as in embedded systems and
device drivers) and in multithreaded applications (though often used incorrectly in that context; see external links at
volatile variable). It can be used in exactly the same manner as const in declarations of variables, pointers,
references, and member functions, and in fact, volatile is sometimes used to implement a similar
design-by-contract strategy which Andrei Alexandrescu calls volatile-correctness,[3] though this is far less
common than const-correctness. The volatile qualifier also can be stripped by const_cast, and it can be
combined with the const qualifier as in this sample:
// Set up a reference to a read-only hardware register that is
// mapped in a hard-coded memory location.
const volatile int & hardwareRegister = *reinterpret_cast<int*>(0x8000);
Const-correctness
40
Const-correctness
final in Java
In Java, the qualifier final states that the affected data member or variable is not assignable, as below:
final int i = 3;
i = 4; // Error! Cannot modify a "final" object
It must be decidable by the compilers where the variable with the final marker is initialized, and it must be
performed only once, or the class will not compile. Java's final and C++'s const keywords have the same
meaning when applied with primitive variables.
const int i = 3; // C++ declaration
i = 4; // Error!
Considering pointers, a final reference in Java means something similar to const pointer in C++. In C++, one
can declare a "const pointer type".
Foo *const bar = mem_location; // const pointer type
Here, bar must be initialised at the time of declaration and cannot be changed again, but what it points is
modifiable. I.e. *bar = value is valid. It just can't point to another location. Final reference in Java work the
same way except it can be declared uninitialized.
final Foo i; // a Java declaration
Note: Java does not support pointers. It is because pointers (with restrictions) are the default way of accessing
objects in Java, and Java does not use stars to indicate them. For example i in the last example is a pointer and can
be used to access the instance.
One can also declare a pointer to "read-only" data in C++.
const Foo *bar;
Here bar can be modified to point anything, anytime; just that pointed value cannot be modified through bar
pointer. There is no equivalent mechanism in Java. Thus there are also no const methods. Const-correctness
cannot be enforced in Java, although by use of interfaces and defining a read-only interface to the class and passing
this around, one can ensure that objects can be passed around the system in a way that they cannot be modified. Java
collections framework provides a way to create unmodifiable wrapper of a Collection via
Collections.unmodifiableCollection() and similar methods.
Methods in Java can be declared "final", but that has a completely unrelated meaning - it means that the method
cannot be overridden in subclasses.
Interestingly, the Java language specification regards const as a reserved keyword i.e., one that cannot be used
as variable identifier but assigns no semantics to it. It is thought that the reservation of the keyword occurred to
allow for an extension of the Java language to include C++-style const methods and pointer to const
type.Wikipedia:Citation needed An enhancement request ticket for implementing const correctness exists in the
Java Community Process, but was closed in 2005 on the basis that it was impossible to implement in a
backwards-compatible fashion.
41
Const-correctness
References
[1] Herb Sutter and Andrei Alexandrescu (2005). C++ Coding Standards. p. 30. Boston: Addison Wesley. ISBN 0-321-11358-6
[2] http:/ / www. stroustrup. com/ bs_faq2. html#whitespace
[3] "Generic<Programming>: volatile Multithreaded Programmer's Best Friend Volatile-Correctness or How to Have Your Compiler Detect
Race Conditions for You" (http:/ / www. drdobbs. com/ cpp/ 184403766) by Andrei Alexandrescu in the C/C++ Users Journal C++ Experts
Forum
External links
"Const-Correctness" (http://gotw.ca/gotw/006.htm) by Herb Sutter
"Constant Optimization?" (http://gotw.ca/gotw/081.htm) by Herb Sutter
"Const-Correctness Tutorial" (http://cprogramming.com/tutorial/const_correctness.html) by
Cprogramming.com
The C++ FAQ Lite: Const correctness (http://parashift.com/c++-faq-lite/const-correctness.html) by Marshall
Cline
Section " Value substitution (http://www.mi.uni-koeln.de/c/mirror/www.codeguru.com/cpp/tic/tic_html.
zip/tic0092.html)" from the free electronic book Thinking in C++ by Bruce Eckel
"Here A Const, There A Const" (http://www.digitalmars.com/d/const.html) by Walter Bright
"Const and Invariant" from D programming language specification, version 2 (experimental) (http://www.
digitalmars.com/d/2.0/const3.html)
Some notes on const correctness in straight C in "C Pointer Qualifiers" (http://www.thomasstover.com/
c_pointer_qualifiers.html) by Thomas Stover
42
Virtual function
43
Virtual function
Polymorphism
Ad hoc polymorphism
Function overloading
Operator overloading
Parametric polymorphism
Double dispatch
Multiple dispatch
Subtyping
Virtual function
v
t
e [1]
In object-oriented programming, a virtual function or virtual method is a function or method whose behavior can
be overridden within an inheriting class by a function with the same signature. This concept is an important part of
the polymorphism portion of object-oriented programming (OOP).
Purpose
Further information: Dynamic dispatch
The concept of the virtual function solves the following problem:
In object-oriented programming when a derived class inherits from a base class, an object of the derived class may
be referred to via a pointer or reference of the base class type instead of the derived class type. If there are base class
methods overridden by the derived class, the method actually called by such a reference or pointer can be bound
either 'early' (by the compiler), according to the declared type of the pointer or reference, or 'late' (i.e. by the runtime
system of the language), according to the actual type of the object referred to.
Virtual functions are resolved 'late'. If the function in question is 'virtual' in the base class, the most-derived class's
implementation of the function is called according to the actual type of the object referred to, regardless of the
declared type of the pointer or reference. If it is not 'virtual', the method is resolved 'early' and the function called is
selected according to the declared type of the pointer or reference.
Virtual functions allow a program to call methods that don't necessarily even exist at the moment the code is
compiled.
In C++, virtual methods are declared by prepending the virtual keyword to the function's declaration in the base
class. This modifier is inherited by all implementations of that method in derived classes, meaning that they can
continue to over-ride each other and be late-bound.
Virtual function
44
Example
For example, a base class Animal
could have a virtual function eat.
Subclass Fish would implement
eat()
differently than subclass
Wolf, but one can invoke eat() on
any class instance referred to as
Animal, and get the eat() behavior
of the specific subclass.
class Animal
{
void /*nonvirtual*/ move() {
cout << "This animal moves in some way" << endl;
}
virtual void eat() {}
};
// The class "Animal" may possess a declaration for eat() if desired.
class Llama : public Animal
{
// The non virtual function move() is inherited but cannot be
overridden
void eat() {
cout << "Llamas eat grass!" << endl;
}
};
This allows a programmer to process a list of objects of class Animal, telling each in turn to eat (by calling
eat()), without needing to know what kind of animal may be in the list, how each animal eats, or what the
complete set of possible animal types might be.
Virtual function
abstract concept whose behaviour is defined solely for each given kind (subclass) of MathSymbol. Similarly, a
given subclass of MathSymbol would not be complete without an implementation of doOperation().
Although pure virtual methods typically have no implementation in the class that declares them, pure virtual methods
in C++ are permitted to contain an implementation in their declaring class, providing fallback or default behaviour
that a derived class can delegate to, if appropriate.
Pure virtual functions can also be used where the method declarations are being used to define an interface - similar
to what the interface keyword in Java explicitly specifies. In such a use, derived classes will supply all
implementations. In such a design pattern, the abstract class which serves as an interface will contain only pure
virtual functions, but no data members or ordinary methods. In C++, using such purely abstract classes as interfaces
works because C++ supports multiple inheritance. However, because many OOP languages do not support multiple
inheritance, they often provide a separate interface mechanism. An example is the Java programming language.
Virtual destructors
Object-oriented languages typically manage memory allocation and de-allocation automatically when objects are
created and destroyed. However, some object-oriented languages allow a custom destructor method to be
implemented, if desired. If the language in question uses automatic memory management, the custom destructor
(generally called a finalizer in this context) that is called is certain to be the appropriate one for the object in
question. For example, if an object of type Wolf that inherits Animal is created, and both have custom destructors,
the one called will be the one declared in Wolf.
In manual memory management contexts, the situation can be more complex, particularly as relates to static
dispatch. If an object of type Wolf is created but pointed to by an Animal pointer, and it is this Animal pointer type
that is deleted, the destructor called may actually be the one defined for Animal and not the one for Wolf, unless the
destructor is virtual. This is particularly the case with C++, where the behavior is a common source of programming
errors.
References
[1] http:/ / en. wikipedia. org/ w/ index. php?title=Template:Polymorphism& action=edit
45
Template (C++)
Template (C++)
Templates 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.
Templates are of great utility to programmers in C++, especially when combined with multiple inheritance and
operator overloading. The C++ Standard Library provides many useful functions within a framework of connected
templates.
Major inspirations for C++ templates were the parametrized modules provided by CLU and the generics provided by
Ada.
Technical overview
There are two kinds of templates: function templates and class templates. (A third kind, variable templates, is
expected to feature in C++14.)
Function templates
A function template behaves like a function except that the template can have arguments of many different types (see
example). In other words, a function template represents a family of functions. The format for declaring function
templates with type parameters is
template <class
identifier> function_declaration;
template <typename identifier> function_declaration;
Both expressions have exactly the same meaning and behave exactly the same way. The latter form was introduced
to avoid confusion because a type parameter does not need to be a class, it may also be a basic type like int or
doubleWikipedia:Citation needed.
For example, the C++ Standard Library contains the function template max(x, y) which returns either x or y,
whichever is larger. max() could be defined with the following template:
//This example throws the following error : call of overloaded
'max(double, double)' is ambiguous
template <typename Type>
Type max(Type a, Type b) {
return a > b ? a : b;
}
This single function definition works with many data types. Although usage of a function template saves space in the
source code file (in addition to limiting changes to one function description) versus separate functions written for
various datatypes, it does not produce smaller object code than would occur from separate non-templated versions of
a function written for different types. For example, if a program uses an int and a double version of the max()
function template shown above, the compiler will create an object code version of max() that takes ints and an object
code version that takes doubles. The compiler output will be identical to what would have been produced if the
source code contained two non-templated versions of max(), one written to handle ints and one written to handle
doubles.
#include <iostream>
int main(int, char**)
{
46
Template (C++)
// This will
std::cout <<
// This will
std::cout <<
// This type
std::cout <<
return 0;
47
call max <int> (by argument deduction)
max(3, 7) << std::endl;
call max<double> (by argument deduction)
max(3.0, 7.0) << std::endl;
is ambiguous, so explicitly instantiate max<double>
max<double>(3, 7.0) << std::endl;
}
In the first two cases, the template argument Type is automatically deduced by the compiler to be int and
double, respectively. In the third case deduction fails because the type of the parameters must in general match the
template arguments exactly. This function template can be instantiated with any copy-constructible type for which
the expression (y < x) is valid. For user-defined types, this implies that the less-than operator must be overloaded.
Class templates
A class template provides a specification for generating classes based on parameters. Class templates are generally
used to implement containers. A class template is instantiated by passing a given set of types to it as template
arguments. The C++ Standard Library contains many class templates, in particular the containers adapted from the
Standard Template Library, such as vector.
Template specialization
When a function or class is instantiated from a template, a specialization of that template is created by the compiler
for the set of arguments used, and the specialization is referred to as being a generated specialization.
Template (C++)
Variadic templates
C++11 introduced variadic templates, which can take a variable number of arguments in a manner somewhat similar
to variadic functions such as std::printf. Both function templates and class templates can be variadic.
48
Template (C++)
49
Template (C++)
50
// Instantiates A
// Instantiates B
Template (C++)
References
[1] Differences Between C++ Templates and C# Generics (C# Programming Guide) (http:/ / msdn2. microsoft. com/ en-us/ library/ c6cyy67b.
aspx)
[2] (D) Templates Revisited (http:/ / dlang. org/ templates-revisited. html)
[3] (D) Template Constraints (http:/ / dlang. org/ concepts. html)
[4] Boost enable_if templates (http:/ / www. boost. org/ doc/ libs/ 1_42_0/ libs/ utility/ enable_if. html)
External links
Demonstration of the Turing-completeness of C++ templates (http://matt.might.net/articles/c++
-template-meta-programming-with-lambda-calculus/) (Lambda calculus implementation)
51
52
53
54
License
License
Creative Commons Attribution-Share Alike 3.0
//creativecommons.org/licenses/by-sa/3.0/
55