Home > Store

C++ Primer, 3rd Edition

Register your product to gain access to bonus material or receive a coupon.

C++ Primer, 3rd Edition

Book

  • Sorry, this book is no longer in print.
Not for Sale

Description

  • Copyright 1998
  • Edition: 3rd
  • Book
  • ISBN-10: 0-201-82470-1
  • ISBN-13: 978-0-201-82470-4

The third edition of the C++ Primer combines Stanley Lippman's practical experience with Josée Lajoie's inside knowledge of the ANSI/ISO Standard C++. This tutorial is rewritten to describe the features and programming usage of Standard C++. Especially useful for developers new to C++ are the many real-world programming examples that illustrate the design of generic and object-oriented programs, the use of templates, and other aspects of program design using Standard C++. In addition, the C++ Primer provides usage and efficiency guidelines where appropriate.

Highlights

  • Clear, practical and example-driven coverage of the Standard Library, with emphasis on the containers, iterators and algorithms (also known as the Standard Template Library), the string class and iostreams
  • A detailed look at the new features of Standard C++; exception handling, run-time type identification, namespaces, the built-in bool type, and new-style cast-notation, with advice on how to effectively use them.
  • A thorough introduction of the advanced language features, such as templates, classes, and inheritance in support of generic programming, object-oriented programming and object-based programming.
  • An appendix that can be used as a quick reference for the generic algorithms, describing their behavior, and providing concrete examples of how to use them.



0201824701B04062001

Downloads

Source Code

Click below for Source Code related to this title:
code.tar.Z

code.zip

Extras

Web Resources

Click below for Web Resources related to this title:
Author's Web Site

Interview(s)

Why did you feel it was time to update the C++ Primer?

Stan: Well, the immediate catalyst, of course, is the completion of Standard C++. Standard C++ represents a major enhancement of the language - there are extensive changes to the template specification, the addition of new features such as namespaces, exception handling, run-time type identification, and the new-style cast notation. In addition, the definition of a standard library alters significantly the way we program - in particular, the string class, and the collection classes and generic algorithms of the Standard Template Library.

JosEe: The second edition of the C++ Primer was published in 1990, as the work of the C++ standard committee was just starting. The work of the committee has changed the definition of C++ in important ways, and with the committee's work coming to an end, the Primer needed to be rewritten to present Standard C++.

What is the most important change to the language since the last edition?

Stan: The most important change to Standard C++ is the inclusion of an extensive standard library, incorporating the Standard Template Library. It fundamentally changes C++ programming under Standard C++. A great deal of the additional material of C++ Primer focuses on the underlying concepts and use of the standard library.

JosEe adds: But the C++ standard library has more to it than just the Standard Template Library. It also includes the iostream library, a string class, and support for locales. The second edition of the Primer did not discuss any library features except for the presentation of the iostream library which was presented in the appendix (back then, in 1990, iostream was all that there was to the C++ library). A big portion of the new material in the Primer presents new features of the C++ standard library. (This is the major reason why the book has grown in size.)

Can you explain what you mean by a "primer"? -- is it a resource a beginning programmer can use?

Stan: A primer provides, through words and examples, a first explanation of the language features and motivates their use. It is a primer in the sense that it provides a consciously tutorial approach to describing the C++ language; it is not a primer in the sense of providing a simplistic description of the language.

Many of the language features are introduced and motivated by stepping through the solution of clearly stated programming problem. So, for example, the discussion of the Standard Template Library container classes and the design and implementation of object-oriented class hierarchies are presented in terms of implementing a text query system. This allows us to step through alternative design choices, and to provide a narrative aspect to our discussion that we believe increases interest in what can be a somewhat dry topic!

JosEe: The Primer is a tutorial on the C++ language features and on the most important aspects of the C++ standard library. The presentation in the book is example-driven. The text presents a feature by showing examples of the kinds of programming problems the feature is supposed to help solve, and then shows how to use the feature in programs to solve the problems discussed.

Not all C++ features are for the beginner programmer. We wanted the book to be an introduction to Standard C++, including an introduction to some features that are more advanced. The book covers more than just the subset of C++ features a beginner programmer uses in the first two weeks of programming in C++. We wanted the book to be used by programmers as they learn new aspects of programming in C++. However, to help the beginner programmers with the material of the Primer, the sections that introduce the more advanced C++ features are marked as such, and the beginner programmer can skip over these sections and come back to them at a later time.

How difficult was it to co-author the book?

Stan: In a film production, the team concept is essential. On the Firebird Suite segment of Fantasia 2000, for example, our Digital Production crew consisted of a Model TD (TD stands for Technical Director), a Software TD (me), and a Look-Dev TD (she writes the light shaders). When it works, the team jells together, each augmenting the work of the other, producing an end result beyond the reach of any of the individuals. I believe this happened in the co-authorship between JosEe and myself.

JosEe: Writing a book is a lot of work. There are moments of dreadful loneliness when one wonders what to do with a piece of text. Having a co-author makes those moments easier because it gives you someone with whom you can share the work, with whom you can bounce ideas. I think I was particularly lucky because Stan and I got along really well. So this co-authorship experience was actually a lot of fun. I could never have come up with a book as good as this one on my own.

If you had the power to unilaterally change any part of the C++ definition, what would you change? Why?

Stan: I would add a "member assignment list" to the class copy assignment operator. Without it, the compiler cannot guarantee to invoke the copy assignment operator of a virtual base class only once. The details of this issue are touched on at the end of Section 5.3 of my Inside the C++ Object Model.

JosEe: I would not change anything. I have been a member of the C++ standard committee for 7 years and I know too well that any small change, even though it looks insignificant, has a very destabilizing effect on the other features of the language and on the features of the library. It took the committee a long time to come up with the C++ definition we have and I think it is pretty good. What I want now is stability, not change. I think the industry needs this stability more than any particular change to teak a minor unpleasant aspect of the C++ definition.

Which C++ features are the most exasperating to implement?

Stan: Virtual base classes. They complicate everything necessary to support the implementation of a class. (Of course, I've missed the chance to implement templates under Standard C++.)

JosEe: Templates. It is not possible to implement templates well using traditional compiler technology. Templates require that some additional tool be present with the compiler to manage template instantiations at the level of the entire program. It is difficult to correctly and efficiently implement this additional tool (which can be a simple prelinker, or, in the most complex systems, a very elaborate development environment).

What are the most common C++ programming mistakes you encounter? -- Which chapters cover these areas?

Stan: In terms of runtime program error, not being aware of when an explicit copy constructor (and copy assignment operator) is required (as well as when it is not). We step through this in detail, with many programming examples, both in Chapter 14 and in Chapter 17 (illustrating the design of an Object-Oriented class hierarchy).

In terms of correct but inefficient programming, it is not being aware of the locality of declaration rule with regard complex class objects (complex class objects have an associated constructor and destructor). While the program executes correctly, it can be significantly slower. This is generally a fault of experienced C programmers because in C all objects must be defined prior to any program statements. This is explained and illustrated in Chapter 5.

JosEe: The mistakes encountered really depend on the background of the programmers we consider.

C programmers new to C++ tend to do the same kind of mistakes. They declare all their objects at the beginning of a block, they do not use classes effectively to package their program data with the functions that manipulate this data, they use switch statements instead of virtual functions. The first chapters of the book will not be of great interest to programmers with a C background. Parts IV and V on object-based and object-oriented programming discuss topics and design issues new to C programmers.

Programmers with experience with other object-oriented languages will have more difficulty with the C-like aspects of C++, such as pointers, and memory management. These topics are discussed in Chapter 3 on basic data types, and again in Chapter 8 on object lifetime.

Other than your own books, what is a "must-have" technical book?

Stan: Bjarne's [Stroustrup] book, of course: The C++ Programming Language. I like to think of the two texts as bookends.

JosEe: The bibliography that is part of the preface of the Primer has a list of C++ books that Stan and I consider important.

Sample Content

Online Sample Chapter

Exception Handling in C++

Downloadable Sample Chapter

Click below for Sample Chapter related to this title:
chap6.pdf

Table of Contents



Preface.


Structure of This Book.


Changes to the Third Edition.


The Future of C++.


Acknowledgments.


Acknowledgments to the Second Edition.


Bibliography.

I. GETTING STARTED.

1. A Journey of 1000 Miles.

Problem Solving.

The C++ Program.

Preprocessor Directives.

A Word About Comments.

A First Look at Input/Output.

2. A Tour of C++.

The Built-In Array Data Type.

Dynamic Memory Allocation and Pointers.

An Object-Based Design.

An Object-Oriented Design.

A Generic Design.

An Exception-Based Design.

An Array by Any Other Name.

The Standard Array Is a Vector.

II. THE BASIC LANGUAGE.

3. Data Types.

Literal Constant.

Variables.

Pointer Types.

String Types.

const Qualifier.

Reference Types.

The bool Type.

Enumeration Types.

Array Types.

The vector Container Type.

complex Number Types.

Typedef Names.

volatile Qualifier.

The pair Type.

Class Types.

4. Expression.

What Is an Expression?

Arithmetic Operators.

Equality, Relational, and Logical Operators.

Assignment Operators.

Increment and Decrement Operators.

Complex Number Operations.

The Conditional Operator.

The sizeof Operator.

The new and delete Expressions.

Comma Operator.

The Bitwise Operators.

bitset Operations.

Precedence.

Type Conversions.

A Stack Class Example.

5. Statements.

Simple and Compound Statements.

Declaration Statement.

The if Statement.

The switch Statement.

The for Loop Statement.

The while Statement.

The do while Statement.

The break Statement.

The continue Statement.

The goto Statement.

A Linked List Example.

6. Abstract Container Types.

Our Text Query System.

A vector or a list?

How a vector Grows Itself.

Defining a Sequence Container.

Our Text Query System.

A vector or a list?

How a vector Grows Itself.

Defining a Sequence Container.

Iterators.

Sequence Container Operations.

Storing Lines of Text.

Finding a Substring.

Handling Punctuation.

A String by Any Other Format.

Additional String Operations.

Building a Text Location Map.

Building a Word Exclusion Set.

The Complete Program.

Multimap and Multiset.

Stack.

Queue and Priority Queue.

Revisiting Our iStack Class Iterators.

Sequence Container Operations.

Storing Lines of Text.

Finding a Substring.

Handling Punctuation.

A String by Any Other Format.

Additional String Operations.

Building a Text Location Map.

Building a Word Exclusion Set.

The Complete Program.

Multimap and Multiset.

Stack.

Queue and Priority Queue.

Revisiting Our iStack Class.

III. PROCEDURAL BASED PROGRAMMING.

7. Functions.

Overview.

Function Prototype.

Argument Passing.

Returning a Value.

Recursion.

Inline Functions.

Linkage Directives: extern “C”.

main(): Handling Command Line Options.

Pointers to Functions.

8. Scope and Lifetime.

Scope.

Global Objects and Functions.

Local Objects.

Dynamically Allocated Objects.

Namespace Definitions.

Using Namespace Members.

9. Overloaded Functions.

Overloaded Function Declarations.

The Three Steps of Overload Resolution.

Argument Type Conversions.

Details of Function Overload Resolution.

10. Function Templates.

Function Template Definition.

Function Template Instantiation.

Template Argument Deduction.

Explicit Template Arguments.

Template Compilation Models.

Template Explicit Specialization.

Overloading Function Templates.

Overload Resolution with Instantiations.

Name Resolution in Template Definitions.

Namespaces and Function Templates.

Function Template Example.

11. Exception handling.

Throwing an Exception.

The Try Block.

Catching an Exception.

Exception Specifications.

Exceptions and Design Issues.

12. Generic Algorithms.

Overview.

Using the Generic Algorithms.

Function Objects.

Revisiting Iterators.

The Generic Algorithms.

When Not to Use the Generic Algorithms.

IV. OBJECT-BASED PROGRAMMING.

13. Classes.

Class Definition.

Class Objects.

Class Member Functions.

The Implicit this Pointer.

Static Class Members.

Pointer to Class Member.

Union: A Space-Saving Class.

Bit-field: A Space-Saving Member.

Class Scope.

Nested Classes.

Classes as Namespace Members.

Local Classes.

14. Initialization, Assignment, and Destruction.

Class Initialization.

The Class Constructor.

The Class Destructor.

Class Object Arrays and Vectors.

The Member Initialization List.

Memberwise Initialization.

Memberwise Assignment.

Efficiency Considerations.

15. Function And Operator Overloading.

Operator Overloading.

Friends.

Operator =.

Operator [ ].

Operator ( ).

Operator ->.

Operators ++ and --.

Operators new and delete.

User-Defined Conversions.

Selecting a Conversion.

Overload Resolution and Member Functions.

Overload Resolution and Operators.

16. Class Templates.

Class Template Definition.

Class Template Instantiation.

Member Functions of Class Templates.

Friend Declarations in Class Templates.

Static Data Members of Class Templates.

Nested Types of Class Templates.

Member Templates.

Class Templates and Compilation Model.

Class Template Specializations.

Class Template Partial Specializations.

Name Resolution in Class Templates.

Namespaces and Class Templates.

A Template Array Class.

V. OBJECT-ORIENTED PROGRAMMING.

17. Class Inheritance and Subtyping.

Defining a Class Hierarchy.

Identifying the Members of the Hierarchy.

Base Class Member Access.

Base and Derived Class Construction.

Base and Derived Class Virtual Functions.

Memberwise Initialization and Assignment.

A UserQuery Manager Class.

Putting It Together.

18. Multiple and Virtual Inheritance.

Setting the Stage.

Multiple Inheritance.

Public, Private, and Protected Inheritance.

Class Scope under Inheritance.

Virtual Inheritance.

A Multiple, Virtual Inheritance Example.

19. Uses of Class Inheritance in C++.

Run-Time Type Identification.

Exceptions and Inheritance.

Overload Resolution and Inheritance.

20. The iostream Library.

The Output Operator<<.

Input.

Additional Input/Output Operators.

Overloading the Output Operator <<.

Overloading the Input Operator >>.

File Input and Output.

Condition States.

String Streams.

Format State.

A Strongly Typed Library.

Appendix: The IOStream Library.

accumulate().

adjacent_difference().

adjacent_find().

binary_search().

copy().

copy_backward().

count().

count_if().

equal().

equal_range().

fill().

fill_n().

find().

find_if().

find_end().

find_first_of().

for_each().

generate().

generate_n().

includes().

inner_product().

inplace_merge().

iter_swap ().

lexicographical_compare().

lower_bound().

max().

max_element().

min().

min_element().

merge().

mismatch().

next_permutation().

nth_element().

partial_sort().

partial_sort_copy().

partial_sum().

partition().

prev_permutation().

random_shuffle().

remove().

remove_copy().

remove_if().

remove_copy_if().

replace().

replace_copy().

replace_if().

replace_copy_if().

reverse().

reverse_copy().

rotate().

rotate_copy().

search().

search_n().

set_difference().

set_intersection().

set_symmetric_difference().

set_union().

sort().

stable_partition().

stable_sort().

swap().

swap_range().

transform().

unique().

unique_copy().

upper_bound().

Heap Algorithms.

make_heap().

pop_heap().

push_heap().

sort_heap().

Index. 0201824701T04062001

Preface

Quite a few changes have occurred between the second and third editions of C++ Primer. Most notably, C++ has undergone international standardization, which has not only added new features to the language, such as exception handling, run-time type identification, namespaces, a built-in Boolean data type, and a new cast notation, but has also extensively modified and extended existing features, such as templates, the class mechanism in support of both object-oriented and object-based programming, nested types, and overload function resolution. Perhaps of even more significance, an extensive library is now part of Standard C++, including what was previously referred to as the Standard Template Library, or STL. A new string type, a set of sequence and associative container types -- such as vector, list, map, and set -- and an extensible collection of generic algorithms to operate on those types are all features of this new standard library. There's not only quite a lot of new material to cover but also new ways to think about how we program in C++. In short, not only has C++ been, in effect, newly invented, but so has the C++ Primer for this, its third edition.

Not only has the treatment of the language changed fundamentally in this third edition, but so has the authorship: in the first place, we've doubled ourselves! Moreover, we've internationalized in the process, although we're firmly rooted in the North American continent: Stan is American; Josée is Canadian. Finally, the twin authorship reflects the twin primary activities of the C++ community: Stan is currently involved in the efficient workplace application of C++ at Walt Disney Feature Animation for 3D computer graphics and animation, while Josée is involved in the definition and implementation of C++, both as chair of the Core Language subcommittee of the standards effort and as a member of the C++ compiler team at the IBM Canada Laboratory.

Stan was one of the original members of the Bell Laboratories team working with Bjarne Stroustrup, the inventor of C++, and has been involved with C++ since 1984. Stan worked on the various implementations of cfront, the original C++ implementation, from Release 1.1 in 1986 through Release 3.0, leading the development team for the 2.1 and 3.0 releases. After that, he worked under Stroustrup on what was known as the Foundation Research Project on the Object Model component of a programming development environment.

Josée has been a member of the C++ compiler team at the IBM Canada Laboratory for eight years. She has been a member of the Standards committee since 1990. She was vice-chair of the committee for three years and has been the chair of the Core Language subcommittee for four years.

C++ Primer, Third Edition, represents an extensive revision of the text to reflect not only the changes and extensions to the language but also changes to the authors' insights and experience.

Structure of This Book

C++ Primer provides a comprehensive introduction to the International Standard on C++. It is a primer in the sense that it provides a consciously tutorial approach to describing the C++ language. (It is not a primer in the sense of providing a simplistic or "gentle" description of the language.) Programming aspects of the language, such as exception handling, the container types, object-oriented programming, and so on, are presented in the context of solving a particular problem or programming task. Language rules, such as the resolution of an overloaded function call or the type conversions supported under object-oriented programming, are given extensive treatment that may initially seem out of place in a primer. We believe that the coverage is necessary to a practical understanding of the language, and we view the material as something one goes back to rather than digests at one sitting. If you find it initially overwhelming or simply too dry, put this material aside until later -- we identify such sections with a special icon in the text.

Knowledge of the C language is not assumed, although familiarity with some modern, block structured language will make the going easier. The book is intended as a first book on C++; it is not intended as a first book on programming! To be sure, we all start with a common vocabulary; however, the initial chapters cover some basic concepts, such as looping statements and variables, that some readers might find too introductory. Not to worry: the depth of coverage picks up quickly.

Much of the power of C++ comes from its support for new ways of programming and thinking about programming problems. Learning to use C++ effectively, therefore, requires more than simply learning a new set of syntax and semantics. To facilitate this larger learning, the book is organized around a series of extended examples. These examples are used both to introduce the details of various language features and to motivate them. When we learn language features in the context of a full example, it becomes clear why such features are useful, providing a sense of when and how we would use them for real-world problem solving. Additionally, this focus on examples allows early use of concepts that will be explained more fully as the reader's knowledge base is built up. Early examples contain simple uses of fundamental C++ concepts, giving a flavor for the kinds of programming one can do in C++ without requiring complete understanding of the details of design and implementation.

Chapters 1 and 2 form a self-contained introduction and overview to the entire C++ language. Part I is intended to get us up to speed on the concepts and language facilities supported by C++ -- and the fundamentals on writing and executing a program. Upon finishing this part of the text, you should have a feel for the language support C++ provides and a sense of not really understanding it at all. That's ok: that's what the rest of the text is for!

Chapter 1 introduces us to the basic elements of the language: the built-in data types, variables, expressions, statements, and functions. It looks at a minimum legal C++ program, briefly discusses the process of compiling our programs, walks through what is spoken of as the preprocessor, and takes a first look at support for input and output. It presents a number of simple but complete C++ programs that the reader is encouraged to compile and execute. Chapter 2 introduces the support C++ provides for object-based and object-oriented programming through the class mechanism, illustrating both through the evolution of an array abstraction. In addition, it briefly introduces templates, namespaces, exception handling, and the standard library support for general container types and generic programming. This chapter is rather fast-paced, and some readers may find it somewhat overwhelming. If that is the case, we suggest you skim through it and return to it later.

Fundamental to C++ are the various facilities that allow the user to extend the language itself by defining new data types that then can be used with the flexibility and simplicity of the built-in data types. The first step to mastery is to understand the base language itself. Chapters 3 through 6 (Part II) introduce the language at this level.

Chapter 3 introduces the built-in and compound data types predefined by the language together with the string, complex, and vector class data types provided by the C++ standard library. These types form the basic building blocks of all our programs. Chapter 4 provides a detailed discussion of the expressions supported by the language, such as the arithmetic, relational, and assignment expressions. Statements, which form the smallest independent unit within a C++ program, are the topic of Chapter 5. The container types provided by the standard C++ library are the focus of Chapter 6. Rather than provide a simple listing of the available operations, we have walked through the implementation of a text query system to illustrate their design and use.

Chapters 7 through 12 (Part III) focus on the procedural-based programming support provided by C++. Chapter 7 introduces the C++ function mechanism. Functions encapsulate a set of operations that generally form a single task, such as print(). (The empty parentheses following a name indicate that it represents a function.) The notions of program scope and lifetime of variables, together with a discussion of the namespace facility, are the topics of Chapter 8. Chapter 9 extends the discussion of functions introduced in Chapter 7 to introduce function overloading. Function overloading allows multiple function instances that provide a common operation (but require differing implementations) to share a common name. For example, we can define a collection of print() functions to output different types of data. Chapter 10 introduces and illustrates the use of function templates. A function template provides a prescription for the automatic generation of a potentially infinite set of function instances varying by type but whose implementations remain invariant.

C++ supports an exception handling facility. An exception represents unexpected program behavior, such as the exhaustion of all available program memory. The portion of the program within which the exception occurs throws an exception -- that is, makes it available to the rest of the program. Some function within the program must then catch the exception and do whatever is necessary. The treatment of exception handling is split across two chapters. In Chapter 11, the basic syntax and use of exception handling are introduced using a simple example of catching and throwing an exception of class type. Because the actual exceptions handled in our programs are usually class objects of an object-oriented class hierarchy, the discussion of how to throw and handle exceptions continues in Chapter 19, after the introduction of object-oriented programming.

Chapter 12 introduces the extensive collection of generic algorithms provided by the standard library and examines how they interact with the container types of Chapter 6 as well as with the built-in array type. The chapter begins by walking through a program design using the generic algorithms. Iterators, introduced in Chapter 6, are discussed further in Chapter 12 because they provide the glue that binds the generic algorithms to the actual containers. The concept of a function object is also introduced and illustrated. Function objects allow us to provide alternative semantics for operators used with the generic algorithms, such as the equality or the less-than operator. The algorithms themselves are detailed, with an illustration of their use, in the Appendix.

Chapters 13 through 16 (Part IV) focus on object-based programming -- that is, the definition and use of the class facility to create independent abstract data types. By creating new types to describe the problem domain, C++ allows the programmer to write applications with much less concern for the various bookkeeping aspects that make programming tedious. The types fundamental to the application can be implemented once and reused, allowing the programmer to concentrate on the problem rather than the details of the implementation. Facilities for encapsulating the data can dramatically simplify subsequent maintenance and evolution of our applications.

Chapter 13 focuses on the general class mechanism: how to define a class, the concept of information hiding -- that is, of separating the public class interface from the private implementation -- and how to define and manipulate object instances of a class, as well as a discussion of class scope, nested classes, and classes as namespace members.

Chapter 14 details the special support C++ provides for the initialization, destruction, and assignment of class objects using special member functions spoken of, respectively, as a constructor, destructor, and copy assignment operator. We also look at the issue of memberwise initialization and copy, in which one class object is initialized or assigned with another object of its class, and the special named return value optimization for the efficient support of memberwise initialization and copy.

Chapter 15 looks at class-specific operator overloading, first presenting general concepts and design considerations and then looking at specific operators, such as the assignment, subscript, call, and class-specific new and delete operators. The notion of a friend to a class with special access permission and why friends are sometimes needed is also presented. User-defined conversions are then discussed, including the underlying concepts and an extensive example of their use. The rules for function overload resolution are also discussed in this chapter in some detail, with extensive illustration by code examples.

Class templates are the topic of Chapter 16. A class template is a prescription for creating a class in which one or more types or values are parameterized. A vector class, for example, may parameterize the type of element it contains. A buffer class may parameterize not only the type of element it holds but also the size of its buffer. In a more sophisticated usage, such as in distributed computing, the IPC interface, addressing interface, and synchronization interface might all be parameterized. This chapter includes discussions on how to define a class template, how to create specific type instances of a class template, how to define the members of a class template (member functions, static members, and nested types), and how to organize our programs using class templates. It concludes with an extended class template example.

Object-oriented programming and the facilities in C++ that support it are the topic of Chapters 17, 18, 19, and 20 (Part IV). Chapter 17 introduces the C++ facilities that support the primary elements of object-oriented programming: inheritance and dynamic binding. In object-oriented programming, parent/child relationships (spoken of as type/subtype relationships) are defined between classes that share common behavior. Rather than reimplement shared characteristics, a class inherits the data and operations of its parent class. The child class, or subtype, programs only its differences with its parent class. For example, we may define a parent Employee class type and two children: TemporaryEmpl and Manager. These subtypes inherit all the behavior of an Employee. They implement the behavior that is unique to each of their respective types.

A second aspect of inheritance, spoken of as polymorphism, is the ability of a parent type to refer to any of the subtypes that are inherited from it. An Employee, for example, can address its own type or that of TemporaryEmpl or Manager. Dynamic binding is the ability to resolve at run-time which operation to execute based on the actual type of the polymorphic object. In C++, this is handled through the virtual function mechanism.

Chapter 17 introduces the basic features of object-oriented programming. It walks through the design and implementation of a Query class hierarchy in support of the text query system we began implementing in Chapter 6.

Chapter 18 introduces the more-complicated inheritance hierarchies that are made possible through multiple and virtual inheritance. It extends the template class example of Chapter 16 into a three-level class template hierarchy using multiple and virtual inheritance.

Chapter 19 introduces the run-time type identification (RTTI) facility. RTTI allows our programs to query a polymorphic class object as to its type during execution of the program. For example, we can ask an Employee object whether it actually addresses a Manager type. In addition, Chapter 19 revisits exception handling to discuss the standard library exception class hierarchy and illustrate defining and handling our own exception class hierarchies. It also provides an in-depth look at the support of overload function resolution in the presence of inheritance.

Chapter 20 illustrates in detail how to use the C++ iostream input/output library. It provides explanation and examples of the general input and output of data, of defining class-specific instances of the input and output operators, of how to recognize and set condition states, and of how to format data. The iostream library is a class hierarchy implemented using both virtual and multiple inheritance.

The C++ Primer concludes with an Appendix that provides a discussion and program example of each generic algorithm in alphabetical order for easy reference.

Finally, whenever one writes a book, what one chooses to leave out is often as important as what one covers. Certain aspects of the language -- such as a detailed discussion of how constructors work, under what conditions internal temporary objects are created by the compiler, or general concerns about efficiency -- do not fit well into a tutorial introduction to the language, although they are of general importance to programming real-world applications. Prior to embarking on a third edition of C++ Primer, Stan wrote Inside the C++ Object Model (see LIPPMAN96a in the Bibliography at the end of this Preface) to cover much of this companion material. Often, the text refers to a discussion within the Object Model when readers may wish to have the more detailed explanation, particularly for the treatment of object-based and object-oriented programming.

Certain portions of the C++ standard library have been intentionally left out, such as the support for locales and the numerical library. The C++ standard library is very extensive, and presenting all its aspects is beyond the scope of this primer. Some of the books in the Bibliography discuss the library in more detail (see MUSSER96 and STROUSTRUP97). We believe that many books on various aspects of the C++ standard library will follow the publication of this book.

Changes to the Third Edition

The changes to the third edition fall into four general categories:

  1. Coverage of new features added to the language: exception handling, run-time type identification, namespaces, the built-in bool type, and new-style cast notation.
  2. Coverage of the new C++ standard library, including the complex and string types, auto_ptr and pair types, the sequence and associative container types (primarily the list, vector, map, and set containers), and generic algorithms.
  3. Adjustments in the existing text to reflect refinements, changes, and extensions to existing language features in Standard C++. An example of a refinement is the ability to forward declare a nested type, previously disallowed by the language. An example of a language change is the ability of a derived class instance of a virtual function to return a type publicly derived from the return type of the base class instance. This change supports a form of class operation spoken of as a clone or factory method (a clone() virtual function is illustrated in Section 17.5.7). An example of an extension to an existing feature is the ability to explicitly specify one or more of the template arguments to a function template. (Actually, templates have been greatly extended, almost to the point of being a new feature!)
  4. Improvements in the treatment and organization of a majority of the advanced language features -- in particular, templates, classes, and the treatment of object-oriented programming. A side effect of Stan having moved from the relatively small C++ provider community into the general C++ user community is, he believes, a deeper insight into the problems otherwise intelligent programmers have in using the C++ language intelligently. Accordingly, in this third edition, we've shifted the focus in many cases to better illustrate the concepts underlying a feature and how best to use it, pointing out potential pitfalls to avoid when appropriate.

The Future of C++

At the time of the publication of this book, the ISO/ANSI C++ Standards committee has completed its technical work for the first International Standard on C++. The Standard will be published by ISO in the summer of 1998.

C++ implementations supporting Standard C++ will be available soon after the publication of the Standard. With the publication of the Standard, the evolution of the C++ language will stabilize. This stability will allow for the development of sophisticated libraries, written in Standard C++, to address industry-specific problems. Thus, the major growth in the C++ world is expected to be in the area of libraries.

Once a Standard is published, the Standards committee nonetheless continues its work, albeit at a slower pace, to address the requests for interpretation provided by the users of the Standard. This will lead to minor clarifications and corrections to the C++ Standard. If need be, an International Standard is revised every five years to take into account the changes in the technology and in the needs of the industry.

What will be done five years after the publication of the C++ Standard is still unknown. It is possible that new library components that are in wide use in the industry will be added to the set of components of the C++ standard library. But for now, with the work of the C++ Standards committee complete, the fate of C++ rests solely in the hands of its users.



0201824701P04062001

Updates

Errata

The following is a list of semantically significant corrections to the C++ Primer that have been made to the 2nd Printing of the text.

Preface

Pg. xx: 2nd Paragraph, last Sentence. Thank you should go to Clovis Tondo, not Clouis Tondo. Our sincere apology.

Chapter 3

Pg. 112: 5th paragraph, 2nd Sentence.

The text Moreover, we can pass it an equivalent integer value, as in
should read:
Moreover, if we pass it an equivalent integer value, as in the following, the compiler still flags it as an error.

Chapter 4

Pg. 171: 2nd full paragraph, 2nd line.

to_long()
should read:
to_ulong()
Pg. 174-175: Precedence table. The horizontal lines separating precedence groupings for some reason were dropped in the final figure. They were added. In addition, the conditional operator (?:) is incorrectly placed above the assignment operator n it should be listed following the compound operators. Mea Culpa.

Chapter 6

Pg. 261: paragraph following 4th code block, 3rd Sentence. The text
The list container also supports push_front()
should read:
The list (and deque) containers also support push_front()

Pg. 262: footnote. The text

If the use of push_front()
should read:
If element insertion at the front

Chapter 7

Pg. 382: code segment, 9 lines from end of page. The initialization of pfCompare should read as follows:
PFI2S (*pfCompare)[2] = &compareFuncs;
Pg. 383: first code segment, should read as follows:
compareFuncs[ 0 ];
(*pfCompare)[ 0 ];

Chapter 8

Pg. 418: the code segment. The if statement in main() should read as follows:
// check that an object was placed in buf
if ( pb->val() == 0 )
    cout << "new expression worked!" << endl;
Pg. 418: 1st paragraph, 1st sentence. The sentence following the code segment should read as follows:
When compiled and executed, this program generates the following output:

new expression worked!

Pg. 424: first code segment. The function func() should read as follows:
void func( cplusplus_primer::matrix &m )
{
// ...
cplusplus_primer::inverse( m );

}

Pg. 427: first code segment. The function func() should read as follows:
void func( cplusplus_primer::MatrixLib::matrix &m )
{
// ...
cplusplus_primer::MatrixLib::inverse( m );

}

Pg. 434: last code segment. The function func() should read as follows:
void func( cplusplus_primer::MatrixLib::matrix &m )
{
// ...
cplusplus_primer::MatrixLib::inverse( m );

}

Pg. 435: first code segment. The function func() should read as follows:
void func( mlib::matrix &m )
{
// ...
mlib::inverse( m );

}

Pg. 435: second code segment. The function func() should read as follows:
void func( Lib::matrix &m )
{
// ...
alias::inverse( m );

}

Pg. 437: the code segment. The function func() should read as follows:
void func( matrix &m )
{
// ...
inverse( m );

}

Pg. 438: first code segment. The function func() should read as follows:
void func( matrix &m )
{
// ...
inverse( m );

}

Chapter 10

Pg. 503: first code segment. The definition of ia_rc in main() should read as follows:
ArrayRC<int> ia_rc( ia, sizeof(ia)/sizeof(int) );
Pg. 544 and Pg. 545: code segment. The calls to sort() in main() should read as follows:
sort( arrd, 0, arrd.size()-1 );

sort( arri, 0, arri.size()-1 );

sort( arrs, 0, arrs.size()-1 );

Chapter 11

Pg. 550: Exercise 11.1. The question (d) should read as follows:
(d) int *pi = &excpObj;

throw pi;

Chapter 12

Pg. 586: the code segment. The code fragment should read as follows:
template <typename Type>
const Type&
min( const Type *p, int size )
{
int minIndex = 0;
for ( int ix = 1; ix < size; ++ix )
if ( p[ ix ] < p[ minIndex ] )
minIndex = ix;
return p[ minIndex ];
}
Pg. 587: the code segment. The top code fragment should read as follows:
template < typename Type,
bool (*Comp)(const Type&, const Type&)>
const Type&
min( const Type *p, int size, Comp comp )
{
int minIndex = 0;
for ( int ix = 1; ix < size; ++ix )
if ( Comp( p[ ix ], p[ minIndex ] ))
minIndex = ix;
return p[ minIndex ];
}
Pg. 588: the code segment. The code fragment should read as follows:
template < typename Type,
typename Comp >
const Type&
min( const Type *p, int size, Comp comp )
{
int minIndex = 0;
for ( int ix = 1; ix < size; ++ix )
if ( Comp( p[ ix ], p[ minIndex ] ))
minIndex = ix;
return p[ minIndex ];
}
Pg. 595: the code segment. The top code fragment should read as follows:
// this fails to compile as implemented
template < typename type >
int
count( const vector< type > &vec, type value )
{
int count = 0;
vector< type >::iterator iter = vec.begin();
while ( iter != vec.end() ) {
if ( *iter == value )
++count;
++iter;
}
return count;
}
Pg. 596: first paragraph, first sentence. The text
... hold the nine integer values
should read:
hold the eight integer values

Chapter 13

Pg. 640: first code segment. The for statement should read as follows:
for ( idx_type ix = 0; ix < _height; ++ix )
{ // for each row
idx_type offset = w * ix; // row position
for ( idx_type iy = 0; iy < _width; ++iy )
// for each column, assign the old value
_screen[ offset + iy ] = local[ local_pos++ ];
}
Pg. 647: the code segment. The second if statement in the function main() should read as follows:
if ( compareRevenue( ac1, &ac2 ) > 0 )
cout << ac1.owner()
<< " is richer than "
<< ac2.owner() << "\n";
else
cout << ac1.owner()
<< " is poorer than "
<< ac2.owner() << "\n";
Pg. 658: Exercise 13.15. The text
... to initialize the data member introduced in Exercise 3.14.
Should read:
... to initialize the data member introduced in Exercise 13.14.

Chapter 15

Pg. 757: first code segment. The constructor definition in class ScreenPtr should read as follows:
ScreenPtr( Screen &s ) : ptr( &s ) { }
Pg. 758: the code segment. The function printScreen() should read as follows:
void printScreen( ScreenPtr &ps )
{
cout << "Screen Object ("
<< ps->height() << ", "
<< ps->width() << " )\n\n";
for ( int ix = 1; ix <= ps->height(); ++ix )
{
for ( int iy = 1; iy <= ps->width(); ++iy )
cout << ps->get( ix, iy );
cout << "\n";
}
}
Pg. 758: the code segment. The for statement in main() should read as follows:
for ( int ix = 1; ix <= ps->height(); ++ix )
for ( int iy = 1; iy <= ps->width(); ++iy )
{
ps->move( ix, iy );
ps-> set( init[ initpos++ ] );
}
Pg. 759: the second code segment. The constructor definition in class ScreenPtr should read as follows:
ScreenPtr( Screen &s, int arraySize = 0 )
: ptr( &s ), size ( arraySize ), offset( 0 ) { }
Pg. 785: first paragraph, first sentence. The text
... the conversion function Token::operator int() ...
Should read:
... the conversion function Number::operator int() ...
Pg. 794: Exercise 15.13. The text
... class SmallInt defined at the beginning of this section ...
Should read:
... class SmallInt defined at the beginning of Section 15.9...

Chapter 16

Pg. 831: first code segment. In class Queue, the declaration for the member function remove() should read as follows:
Type remove();

Chapter 18

Pg. 967: Figure 18.1. The leaf class nodes,
RPointLight, RSpotLight, and RDirectionalLight
should read
RiPointLight, RiSpotLight, and RiDirectionalLight.
Pg. 1001: Figure 18.5. The derivation line connecting Bear and ZooAnimal should be dotted to indicate a virtual derivation.

Chapter 20

Pg. 1066: last code fragment. The line
string version( 0.01 );
should read:
string version( "0.01" );
Pg. 1071: first sentence, second line. Typo
boolapha();
should read:
boolalpha();
Pg. 1072: first code fragment, 4th line from end. The line
ostream_iterator< string > output( cout, "" );
should read:
ostream_iterator< string > output( cout, " " );
Pg. 1082: 2nd code fragment, 14th line from end. The comment
// max_elements is a generic algorithm
should read:
// max_element is a generic algorithm
Pg. 1085: top code fragment. It should read
int ch;
// alternatively:
// while (( ch = cin.get()) && ch != EOF )
while (( ch = cin.get()) != EOF )
cout.put(ch);

return 0;
}
Pg. 1092: top code fragment. It should read
public:
Location( int line=0, int col=0 )
: _line( line ), _col( col ) {}
private:
short _line;
short _col;
};

ostream& operator <<( ostream& os, const Location& lc )

Pg. 1106: footnote. Back reference to previous exercises should read
Exercise 20.10 or the CheckoutRecord class of Exercise 20.11 (both in Section 20.5) ...
Pg. 1110: last code fragment, fifth line from bottom. It should read
// ok: converts values to a string representation
format_message << "ival: " << ival
<< " ival's address: " << pival << '\n'
<< "dval: " << dval
<< " dval's address: " << pdval << endl;

string msg = format_message.str();
Pg. 1117: 2nd paragraph, first line. It should read
If we should wish to have the 'e' of the scientific notation output display as 'E',
Pg. 1118: bullet item 4, last sentence. It should read
cout is predefined to be tied to cin:

Appendix

Pg. 1141: last line of program illustrating find(). The line
( found_it ? "found!\n" : "not found!\n" );
should read:
( iter != slist.end() ? "found!\n" : "not found!\n" );
Pg. 1156: in description of the max() algorithm. In a leap of inattention, we wrote that it returned the smaller of the two elements. Of course, it returns the larger.

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020