BN.com Gift Guide

C++ Primer / Edition 5

Paperback (Print)
Rent
Rent from BN.com
$18.34
(Save 72%)
Est. Return Date: 02/19/2015
Used and New from Other Sellers
Used and New from Other Sellers
from $37.25
Usually ships in 1-2 business days
(Save 42%)
Other sellers (Paperback)
  • All (14) from $37.25   
  • New (12) from $39.89   
  • Used (2) from $37.25   

Overview

Bestselling Programming Tutorial and Reference Completely Rewritten for the New C++11 Standard

Fully updated and recast for the newly released C++11 standard, this authoritative and comprehensive introduction to C++ will help you to learn the language fast, and to use it in modern, highly effective ways. Highlighting today’s best practices, the authors show how to use both the core language and its standard library to write efficient, readable, and powerful code.

C++ Primer, Fifth Edition, introduces the C++ standard library from the outset, drawing on its common functions and facilities to help you write useful programs without first having to master every language detail. The book’s many examples have been revised to use the new language features and demonstrate how to make the best use of them. This book is a proven tutorial for those new to C++, an authoritative discussion of core C++ concepts and techniques, and a valuable resource for experienced programmers, especially those eager to see C++11 enhancements illuminated.

Start Fast and Achieve More

  • Learn how to use the new C++11 language features and the standard library to build robust programs quickly, and get comfortable with high-level programming
  • Learn through examples that illuminate today’s best coding styles and program design techniques
  • Understand the “rationale behind the rules”: why C++11 works as it does
  • Use the extensive crossreferences to help you connect related concepts and insights
  • Benefit from up-to-date learning aids and exercises that emphasize key points, help you to avoid pitfalls, promote good practices, and reinforce what you’ve learned

Access the source code for the extended examples from informit.com/title/0321714113

C++ Primer, Fifth Edition, features an enhanced, layflat binding, which allows the book to stay open more easily when placed on a flat surface. This special binding method—notable by a small space inside the spine—also increases durability.


This classic and definitive text on the C++ language has been extensively revised and expanded. In its third edition, it is based on the final draft specification of ANSI/ISO Standard. Be forewarned, this is a primer in name only; there is nothing simplistic in its presentation or in its breadth and scope. Knowledge of C is NOT assumed, but knowledge of object-oriented programming and a modern language will make this text more understandable. As the authors point out, "This book is intended as a first book on C++; it is not intended as a first book on programming!"

Read More Show Less

Editorial Reviews

Booknews
The most important new addition to the C++ language is templates, a feature that facilitates the development of extensive class and algorithmic libraries. This second edition provides coverage of this and the other features of Release 3.0. Assumes only an understanding of the basic constructs of a programming language. Annotation c. Book News, Inc., Portland, OR (booknews.com)
Read More Show Less

Product Details

  • ISBN-13: 9780321714114
  • Publisher: Addison-Wesley
  • Publication date: 8/20/2012
  • Edition description: New Edition
  • Edition number: 5
  • Pages: 976
  • Sales rank: 116,505
  • Product dimensions: 9.20 (w) x 7.00 (h) x 2.10 (d)

Meet the Author

Stanley B. Lippman has retired back to the Catalina Foothills where he is working on EEEK!, a computational model of the nervous system of the House Mouse, and An Off By One Error, a speculative novel set in the Northwestern Rain Forest. During his professional career, Stanley served as Distinguished Consultant for the Jet Propulsion Laboratory, Architect for the Visual C++ development group at Microsoft, member of technical staff at Bell Laboratories, two stints in Massive Multiplayer Online Gaming, and a surprisingly long stint in Feature Animation at Disney, DreamWorks, Pixar, and PDI. Stanley will be most remembered for his many years working with Dr. Stroustrup on the implementation of cfront, the standard implementation of C++ until the ISO standard.

Josée Lajoie, now at Pixar, was a member of IBM Canada’s C/C++ compiler development team, and chaired the core language working group for the original ANSI/ISO C++ standardization committee.

Barbara E. Moo has nearly thirty years of software experience. During her fifteen years at AT&T, she worked closely with C++ inventor Bjarne Stroustrup and managed the C++ development team for several years.

Read More Show Less

Read an Excerpt

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.



Read More Show Less

Table of Contents

Preface xxiii

Chapter 1: Getting Started 1

1.1 Writing a Simple C++ Program 2

1.2 A First Look at Input/Output 5

1.3 A Word About Comments 9

1.4 Flow of Control 11

1.5 Introducing Classes 19

1.6 The Bookstore Program 24

Chapter Summary 26

Defined Terms 26

Part I: The Basics 29

Chapter 2: Variables and Basic Types 31

2.1 Primitive Built-in Types 32

2.2 Variables 41

2.3 Compound Types 50

2.4 const Qualifier 59

2.5 Dealing with Types 67

2.6 Defining Our Own Data Structures 72

Chapter Summary 78

Defined Terms 78

Chapter 3: Strings, Vectors, and Arrays 81

3.1 Namespace using Declarations 82

3.2 Library string Type 84

3.3 Library vector Type 96

3.4 Introducing Iterators 106

3.5 Arrays 113

3.6 Multidimensional Arrays 125

Chapter Summary 131

Defined Terms 131

Chapter 4: Expressions 133

4.1 Fundamentals 134

4.2 Arithmetic Operators 139

4.3 Logical and Relational Operators 141

4.4 Assignment Operators 144

4.5 Increment and Decrement Operators 147

4.6 The Member Access Operators 150

4.7 The Conditional Operator 151

4.8 The Bitwise Operators 152

4.9 The sizeof Operator 156

4.10 Comma Operator 157

4.11 Type Conversions 159

4.12 Operator Precedence Table 166

Chapter Summary 168

Defined Terms 168

Chapter 5: Statements 171

5.1 Simple Statements 172

5.2 Statement Scope 174

5.3 Conditional Statements 174

5.4 Iterative Statements 183

5.5 Jump Statements 190

5.6 try Blocks and Exception Handling 193

Chapter Summary 199

Defined Terms 199

Chapter 6: Functions 201

6.1 Function Basics 202

6.2 Argument Passing 208

6.3 Return Types and the return Statement 222

6.4 Overloaded Functions 230

6.5 Features for Specialized Uses 236

6.6 Function Matching 242

6.7 Pointers to Functions 247

Chapter Summary 251

Defined Terms 251

Chapter 7: Classes 253

7.1 Defining Abstract Data Types 254

7.2 Access Control and Encapsulation 268

7.3 Additional Class Features 271

7.4 Class Scope 282

7.5 Constructors Revisited 288

7.6 static Class Members 300

Chapter Summary 305

Defined Terms 305

Part II: The C++ Library 307

Chapter 8: The IO Library 309

8.1 The IO Classes 310

8.2 File Input and Output 316

8.3 string Streams 321

Chapter Summary 324

Defined Terms 324

Chapter 9: Sequential Containers 325

9.1 Overview of the Sequential Containers 326

9.2 Container Library Overview 328

9.3 Sequential Container Operations 341

9.4 How a vector Grows 355

9.5 Additional string Operations 360

9.6 Container Adaptors 368

Chapter Summary 372

Defined Terms 372

Chapter 10: Generic Algorithms 375

10.1 Overview 376

10.2 A First Look at the Algorithms 378

10.3 Customizing Operations 385

10.4 Revisiting Iterators 401

10.5 Structure of Generic Algorithms 410

10.6 Container-Specific Algorithms 415

Chapter Summary 417

Defined Terms 417

Chapter 11: Associative Containers 419

11.1 Using an Associative Container 420

11.2 Overview of the Associative Containers 423

11.3 Operations on Associative Containers 428

11.4 The Unordered Containers 443

Chapter Summary 447

Defined Terms 447

Chapter 12: Dynamic Memory 449

12.1 Dynamic Memory and Smart Pointers 450

12.2 Dynamic Arrays 476

12.3 Using the Library: A Text-Query Program 484

Chapter Summary 491

Defined Terms 491

Part III: Tools for Class Authors 493

Chapter 13: Copy Control 495

13.1 Copy, Assign, and Destroy 496

13.2 Copy Control and Resource Management 510

13.3 Swap 516

13.4 A Copy-Control Example 519

13.5 Classes that Manage Dynamic Memory 524

13.6 Moving Objects 531

Chapter Summary 549

Defined Terms 549

Chapter 14: Overloaded Operations and Conversions 551

14.1 Basic Concepts 552

14.2 Input and Output Operators 556

14.3 Arithmetic and Relational Operators 560

14.4 Assignment Operators 563

14.5 Subscript Operator 564

14.6 Increment and Decrement Operators 566

14.7 Member Access Operators 569

14.8 Function-Call Operator 571

14.9 Overloading, Conversions, and Operators 579

Chapter Summary 590

Defined Terms 590

Chapter 15: Object-Oriented Programming 591

15.1 OOP: An Overview 592

15.2 Defining Base and Derived Classes 594

15.3 Virtual Functions 603

15.4 Abstract Base Classes 608

15.5 Access Control and Inheritance 511

15.6 Class Scope under Inheritance 617

15.7 Constructors and Copy Control 622

15.8 Containers and Inheritance 630

15.9 Text Queries Revisited 634

Chapter Summary 649

Defined Terms 649

Chapter 16: Templates and Generic Programming 651

16.1 Defining a Template 652

16.2 Template Argument Deduction 678

16.3 Overloading and Templates 694

16.4 Variadic Templates 699

16.5 Template Specializations 706

Chapter Summary 713

Defined Terms 713

Part IV: Advanced Topics 715

Chapter 17: Specialized Library Facilities 717

17.1 The tuple Type 718

17.2 The bitset Type 723

17.3 Regular Expressions 728

17.4 Random Numbers 745

17.5 The IO Library Revisited 752

Chapter Summary 769

Defined Terms 769

Chapter 18: Tools for Large Programs 771

18.1 Exception Handling 772

18.2 Namespaces 785

18.3 Multiple and Virtual Inheritance 802

Chapter Summary 816

Defined Terms 816

Chapter 19: Specialized Tools and Techniques 819

19.1 Controlling Memory Allocation 820

19.2 Run-Time Type Identification 825

19.3 Enumerations 832

19.4 Pointer to Class Member 835

19.5 Nested Classes 843

19.6 Union: A Space-Saving Class 847

19.7 Local Classes 852

19.8 Inherently Nonportable Features 854

Chapter Summary 862

Defined Terms 862

Appendix A: The Library 865

A.1 Library Names and Headers 866

A.2 A Brief Tour of the Algorithms 870

A.3 Random Numbers 882

Index 887

Read More Show Less

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 WaltDisney 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.



Read More Show Less

Customer Reviews

Average Rating 5
( 2 )
Rating Distribution

5 Star

(2)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing all of 2 Customer Reviews
  • Anonymous

    Posted September 27, 2014

    Great book but DO NOT BUY FROM BARNES AND NOBLE!

    This book is a great text to go through after a beginners textbook. It could even serve as a reference. Do not buy from B&N. It took them about a month to deliver the book although they promised a 3-5 day shipping.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted February 10, 2013

    Very good book

    It is the best book when learning C++. But it is not easy to understand at beginning. For those very beginners, another book named"essential c++" may be more suitable.
    PS: I wonder that why the most recent review of this book is posted ten years ago...?

    0 out of 1 people found this review helpful.

    Was this review helpful? Yes  No   Report this review
Sort by: Showing all of 2 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)