“The chief merit of language is clearness ”
Welcome to C++ and C++ How to Program, Fifth Edition! C++ is a world-class programming language for developing industrial-strength, high-performance computer applications. We believe that this book and its support materials have everything instructors and students need for an informative, interesting, challenging and entertaining C++ educational experience. In this Preface, we overview the many new features of C++ How to Program, 5/e. The Tour of the Book section of the Preface gives instructors, students and professionals a sense of C++ How to Program, 5/e’s coverage of C++ and object-oriented programming. We also overview various conventions used in the book, such as syntax coloring the code examples, “code washing” and code highlighting. We provide information about free compilers that you can find on the Web. We also discuss the comprehensive suite of educational materials that help instructors maximize their students’ learning experience, including the Instructor’s Resource CD, PowerPoint Slide lecture notes, course management systems, SafariX (Pearson Education’s WebBook publications) and more.
Features of C++ How to Program, 5/e
At Deitel & Associates, we write college-level computer science textbooks and professional books. To create C++ How to Program, 5/e, we put the previous edition of C++ How to Program under the microscope. The new edition has many compelling features:
• Major Content Revisions. All the chapters have been significantly updated and upgraded. We tuned the writing for clarity and precision. We also adjusted our use of C++ terminology in accordance with the ANSI/ISO C++ standard document that defines the language.
• Smaller Chapters. Larger chapters have been divided into smaller, more manageable chapters (e.g., Chapter 1 of the Fourth Edition has been split into Chapters 1–2; Chapter 2 of the Fourth Edition is now Chapters 4–5).
• Early Classes and Objects Approach. We changed to an early classes and objects pedagogy. Students are introduced to the basic concepts and terminology of object technology in Chapter 1. In the previous edition, students began developing customized, reusable classes and objects in Chapter 6, but in this edition, they do so in our completely new Chapter 3. Chapters 4–7 have been carefully rewritten from an “early classes and objects” perspective. This new edition is object oriented, where appropriate, from the start and throughout the text. Moving the discussion of objects and classes to earlier chapters gets students “thinking about objects” immediately and mastering these concepts more completely. Object-ori• ented programming is not trivial by any means, but it’s fun to write object-oriented programs, and students can see immediate results.
• Integrated Case Studies. We have added several case studies spanning multiple sections and chapters that often build on a class introduced earlier in the book to demonstrate new programming concepts later in the book. These case studies include the development of the GradeBook class in Chapters 3–7, the Time class in several sections of Chapters 9–10, the Employee class in Chapters 12–13, and the optional OOD/UML ATM case study in chapters 1-7, 9, 13 and Appendix G.
• Integrated GradeBook Case Study. We added a new GradeBook case study to reinforce our early classes presentation. It uses classes and objects in Chapters 3–7 to incrementally build a GradeBook class that represents an instructor’s grade book and performs various calculations based on a set of student grades, such as calculating the average grade, finding the maximum and minimum and printing a bar chart.
• Unified Modeling Language 2.0 (UML 2.0)—Introducing the UML 2.0. The Unified Modeling Language (UML) has become the preferred graphical modeling language for designers of object-oriented systems. All the UML diagrams in the book comply with the new UML 2.0 specification. We use UML class diagrams to visually represent classes and their inheritance relationships, and we use UML activity diagrams to demonstrate the flow of control in each of C++’s control statements. We make especially heavy use of the UML in the optional OOD/UML ATM case study
• Optional OOD/UML ATM Case Study. We replaced the optional elevator simulator case study from the previous edition with a new optional OOD/UML automated teller machine (ATM) case study in the Software Engineering Case Study sections of Chapters 1–7, 9 and 13. The new case study is simpler, smaller, more “real world” and more appropriate for first and second programming courses. The nine case study sections present a carefully paced introduction to object-oriented design using the UML. We introduce a concise, simplified subset of the UML 2.0, then guide the reader through a first design experience intended for the novice object-oriented designer/programmer. Our goal in this case study is to help students develop an object-oriented design to complement the object-oriented programming concepts they begin learning in Chapter 1 and implementing in Chapter 3. The case study was reviewed by a distinguished team of OOD/UML academic and industry professionals. The case study is not an exercise; rather, it is a fully developed end-to-end learning experience that concludes with a detailed walkthrough of the complete 877-line C++ code implementation. We take a detailed tour of the nine sections of this case study later in the Preface.
• Compilation and Linking Process for Multiple-Source-File Programs. Chapter 3 includes a detailed diagram and discussion of the compilation and linking process that produces an executable application.
• Function Call Stack Explanation. In Chapter 6, we provide a detailed discussion (with illustrations) of the function call stack and activation records to explain how C++ is able to keep track of which function is currently executing, how au• tomatic variables of functions are maintained in memory and how a function knows where to return after it completes execution.
• Early Introduction of C++ Standard Library string and vector Objects. The string and vector classes are used to make earlier examples more object-oriented.
• Class string. We use class string instead of C-like pointer-based char * strings for most string manipulations throughout the book. We continue to include discussions of char * strings in Chapter 8, 10, 11 and 22 to give students practice with pointer manipulations, to illustrate dynamic memory allocation with new and delete, to build our own String class, and to prepare students for assignments in industry where they will work with char * strings in C and C++ legacy code.
• Class Template vector. We use class template vector instead of C-like pointer-based array manipulations throughout the book. However, we begin by discussing C-like pointer-based arrays in Chapter 7 to prepare students for working with C and C++ legacy code in industry and to use as a basis for building our own customized Array class in Chapter 11, Operating Overloading.
• Tuned Treatment of Inheritance and Polymorphism. Chapters 12–13 have been carefully tuned, making the treatment of inheritance and polymorphism clearer and more accessible for students who are new to OOP. An Employee hierarchy replaces the Point/Circle/Cylinder hierarchy used in prior editions to introduce inheritance and polymorphism. The new hierarchy is more natural.
• Discussion and Illustration of How Polymorphism Works “Under the Hood.” Chapter 13 contains a detailed diagram and explanation of how C++ can implement polymorphism, virtual functions and dynamic binding internally. This gives students a solid understanding of how these capabilities really work. More importantly, it helps students appreciate the overhead of polymorphism—in terms of additional memory consumption and processor time. This helps students determine when to use polymorphism and when to avoid it.
• Web Programming. Chapter 19, Web Programming, has everything readers need to begin developing their own Web-based applications that will run on the Internet! Students will learn how to build so-called n-tier applications, in which the functionality provided by each tier can be distributed to separate computers across the Internet or executed on the same computer. Using the popular Apache HTTP server (which is available free for download from www.apache.org) we present the CGI (common Gateway Interface) protocol and discuss how CGI allows a Web server to communicate with the top tier (e.g., a Web browser running on the user’s computer) and CGI scripts (i.e., our C++ programs) executing on a remote system. The chapter examples conclude with an e-business case study of an online bookstore that allows users to add books to an electronic shopping cart.
• Standard Template Library (STL). This might be one of the most important topic in the book in terms of your appreciation of software reuse. The STL defines powerful, template-based, reusable components that implement many common data structures and algorithms used to process those data structures. Chapter 23 introduces the STL and discusses its three key components—containers, iterators and algorithms. We show that using STL components provides • tremendous expressive power and can reduce many lines of code to a single statement.
• XHTML. The World Wide Web Consortium (W3C) has declared HyperText Markup Language (HTML) to be a legacy technology that will undergo no further development. HTML is being replaced by the Extensible HyperText Markup Language (XHTML)—an XML-based technology that rapidly is becoming the standard for describing Web content. We use XHTML in Chapter 19, Web Programming; Appendix J and Appendix K introduce XHTML.
• ANSI/ISO C++ Standard Compliance. We have audited our presentation against the most recent ANSI/ISO C++ standard document for completeness and accuracy. [Note: If you need additional technical details on C++, you may want to read the C++ standard document. An electronic PDF copy of the C++ standard document, number INCITS/ISO/IEC 14882-2003, is available for $18 at webstore.ansi.org/ansidocstore/default.asp.]
• New Debugger Appendices. We include two new Using the Debugger appendices—Appendix L, Using the Visual Studio .NET Debugger, and Appendix M, Using the GNU C++ Debugger.
• New Interior Design. Working with the creative services team at Prentice Hall, we redesigned the interior styles for our How to Program Series. The new fonts are easier on the eyes and the new art package is more appropriate for the more detailed illustrations. We now place the defining occurrence of each key term both in the text and in the index in blue, bold style text for easier reference. We emphasize on-screen components in the bold Helvetica font (e.g., the File menu) and emphasize C++ program text in the Lucida font (e.g., int x = 5).
• Syntax Coloring. We syntax color all the C++ code, which is consistent with most C++ integrated development environments and code editors. This greatly improves code readability—an especially important goal, given that this book contains 17,292 lines of code. Our syntax-coloring conventions are as follows:
keywords appear in dark blue
constants and literal values appear in light blue
errors appear in red
all other code appears in black
• Code Highlighting. Extensive code highlighting makes it easy for readers to locate each program’s new features and helps students review the material rapidly when preparing for exams or labs.
• “Code washing.” This is our term for using extensive and meaningful comments, using meaningful identifiers, applying uniform indentation conventions, aligning curly braces vertically, using a // end... comment on every line with a right curly brace and using vertical spacing to highlight significant program units such as control statements and functions. This process results in programs that are easy to read and self-documenting. We have extensively “code washed” all of the source-code programs in both the text and the book’s ancillaries. We have worked hard to make our code exemplary.
• Code Testing on Multiple Platforms. We tested the code examples on various popular C++ platforms. For the most part, all of the book’s examples port easily to all popular ANSI/ISO standard-compliant compilers. We will post any problems at www.deitel.com/books/cpphtp5/index.html.
• Errors and Warnings Shown for Multiple Platforms. For programs that intentionally contain errors to illustrate a key concept, we show the error messages that result on several popular platforms.
• Large Review Team. The book has been carefully scrutinized by a team of 30 distinguished academic and industry reviewers (listed later in the Preface).
• Free Web-Based Cyber Classroom. We’ve converted our popular interactive multimedia version of the text (which we call a Cyber Classroom) from a for-sale, CD-based product to a free online supplement, available with new books purchased from Prentice Hall for fall 2005 classes.
• Free Student Solutions Manual. We’ve converted our Student Solutions Manual, which contains solutions to approximately half of the exercises, from a for-sale softcover book to a free online supplement, available with new books purchased from Prentice Hall for fall 2005 classes.
• Free Lab Manual. We’ve converted our Lab Manual, C++ in the Lab, from a for-sale softcover book to a free online supplement included with the Cyber Classroom, available with new books purchased from Prentice Hall for fall 2005 classes.
As you read this book, if you have questions, send an e-mail to email@example.com; we will respond promptly. Please visit our Web site, www.deitel.com and be sure to sign up for the free Deitel Buzz Online e-mail newsletter at www.deitel.com/newsletter/subscribe.html for updates to this book and the latest information on C++. We also use the Web site and the newsletter to keep our readers and industry clients informed of the latest news on Deitel publications and services. Please check the following Web site regularly for errata, updates regarding the C++ software, free downloads and other resources:
C++ How to Program, 5/e contains an abundant collection of examples, exercises and projects drawn from many fields to provide the student with a chance to solve interesting real-world problems. The book concentrates on the principles of good software engineering and stresses program clarity. We avoid arcane terminology and syntax specifications in favor of teaching by example. We are educators who teach programming languages courses in industry classrooms worldwide. Dr. Harvey M. Deitel has 20 years of college teaching experience, including serving as chairman of the Computer Science Department at Boston College, and 15 years of industry teaching experience. Paul Deitel has 12 years of industry teaching experience. The Deitels have taught C++ courses at all levels to the government, industry, military and academic clients of Deitel & Associates.
Learning C++ using the Live-Code Approach
C++ How to Program, 5/e, is loaded with C++ programs—each new concept is presented in the context of a complete working C++ program that is immediately followed by one or more sample executions showing the program’s inputs and outputs. This style exemplifies the way we teach and write about programming. We call this method of teaching and writing the Live-Code Approach. We use programming languages to teach programming languages. Reading the examples in the text is much like typing and running them on a computer. We provide all the source code for the book’s examples on the accompanying CD and at www.deitel.com—making it easy for students to run each example as they study it.
World Wide Web Access
All the source-code examples for C++ How to Program, 5/e (and our other publications) are available on the Internet as downloads from
Registration is quick and easy, and the downloads are free. We suggest downloading all the examples (or copying them from the CD included in the back of this book), then running each program as you read the corresponding text. Making changes to the examples and immediately seeing the effects of those changes is a great way to enhance your C++ learning experience.
Each chapter begins with a statement of objectives. This lets students know what to expect and gives them an opportunity, after reading the chapter, to determine if they have met these objectives. This is a confidence builder and a source of positive reinforcement.
The learning objectives are followed by quotations. Some are humorous, some philosophical and some offer interesting insights. We hope that you will enjoy relating the quotations to the chapter material. Many of the quotations are worth a second look after reading the chapter.
The chapter outline helps students approach the material in a top-down fashion, so they can anticipate what is to come, and set a comfortable and effective learning pace.
17,292 Lines of Syntax-Colored Code in 260 Example Programs with Program Inputs and Outputs)
Our Live-Code programs range in size from just a few lines of code to more substantial examples. Each program is followed by a window containing the input/output dialogue produced when the program is run, so students can confirm that the programs run as expected. Relating outputs to the program statements that produce them is an excellent way to learn and to reinforce concepts. Our programs demonstrate the diverse features of C++. The code is line-numbered and syntax colored—with C++ keywords, comments and other program text each appearing in different colors. This facilitates reading the code—students will especially appreciate the syntax coloring when they read the larger programs.
An abundance of charts, tables, line drawings, programs and program outputs is included. We model the flow of control in control statements with UML activity diagrams. UML class diagrams model the data members, constructors and member functions of classes. We use additional types of UML diagrams throughout our optional OOD/UML ATM Software Engineering Case Study.
571 Programming Tips
We include programming tips to help students focus on important aspects of program development. We highlight these tips in the form of Good Programming Practices, Common Programming Errors, Performance Tips, Portability Tips, Software Engineering Observations and Error-Prevention Tips. These tips and practices represent the best we have gleaned from a combined six decades of programming and teaching experience. One of our students, a mathematics major, told us that she feels this approach is like the highlighting of axioms, theorems, lemmas and corollaries in mathematics books—it provides a basis on which to build good software.
Good Programming Practices
i.0Good Programming Practices are tips for writing clear programs. These techniques help students produce programs that are more readable, self-documenting and easier to maintain.
Common Programming Errors
i.0Students who are new to programming (or a programming language) tend to make certain errors frequently. Focusing on these Common Programming Errors reduces the likelihood that students will make the same mistakes and shortens long lines outside instructors’ offices during office hours!
iIn our experience, teaching students to write clear and understandable programs is by far the most important goal for a first programming course. But students want to write the programs that run the fastest, use the least memory, require the smallest number of keystrokes or dazzle in other nifty ways. Students really care about performance. They want to know what they can do to “turbo charge” their programs. So we highlight opportunities for improving program performance—making programs run faster or minimizing the amount of memory that they occupy.
i.0Software development is a complex and expensive activity. Organizations that develop software must often produce versions customized to a variety of computers and operating systems. So there is a strong emphasis today on portability, i.e., on producing software that will run on a variety of computer systems with few, if any, changes. Some programmers assume that if they implement an application in standard C++, the application will be portable. This simply is not the case. Achieving portability requires careful and cautious design. There are many pitfalls. We include Portability Tips to help students write portable code and to provide insights on how C++ achieves its high degree of portability.
Software Engineering Observations
i.0The object-oriented programming paradigm necessitates a complete rethinking of the way we build software systems. C++ is an effective language for achieving good software engineering. The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems. Much of what the student learns here will be useful in upper-level courses and in industry as the student begins to work with large, complex real-world systems.
i.0When we first designed this “tip type,” we thought we would use it strictly to tell people how to test and debug C++ programs. In fact, many of the tips describe aspects of C++ that reduce the likelihood of “bugs” and thus simplify the testing and debugging processes.
Each chapter ends with additional pedagogical devices. New in this edition, each chapter ends with a brief “wrap-up” section that recaps the topics that were presented. The wrap-ups also help the student transition to the next chapter.
Summary (1126 Summary bullets)
We present a thorough, bullet-list-style summary at the end of every chapter. On average, there are 40 summary bullets per chapter. This focuses the student’s review and reinforces key concepts.
Terminology (1682 Terms)
We include an alphabetized list of the important terms defined in each chapter—again, for further reinforcement. There is an average of 82 terms per chapter. Each term also appears in the index, and the defining occurrence of each term is highlighted in the index with a blue, bold page number so the student can locate the definitions of key terms quickly.
609 Self-Review Exercises and Answers (Count Includes Separate Parts)
Extensive self-review exercises and answers are included in each chapter. This gives the student a chance to build confidence with the material and prepare for the regular exercises. We encourage students to do all the self-review exercises and check their answers.
849 Exercises (Solutions in Instructor’s Manual; Count Includes Separate Parts)
Each chapter concludes with a substantial set of exercises including simple recall of important terminology and concepts; writing individual C++ statements; writing small portions of C++ functions and classes; writing complete C++ functions, classes and programs; and writing major term projects. The large number of exercises enables instructors to tailor their courses to the unique needs of their audiences and to vary course assignments each semester. Instructors can use these exercises to form homework assignments, short quizzes and major examinations. The solutions for the vast majority of the exercises are included on the Instructor’s Resource CD (IRCD), which is available only to instructors through their Prentice Hall representatives. [NOTE: Please do not write to us requesting the Instructor’s CD. Distribution of this ancillary is limited strictly to college instructors teaching from the book. Instructors may obtain the solutions manual only from their Prentice Hall representatives.] Students will have access to approximately half the exercises in the book in the free, Web-based Cyber Classroom which will be available in late spring 2005. For more information about the Cyber Classroom, please visit www.deitel.com or sign up for the free Deitel Buzz Online e-mail newsletter at www.deitel.com/newsletter/subscribe.html.
Approximately 6,000 Index Entries
We have included an extensive index. This helps students find terms or concepts by keyword. The index is useful to people reading the book for the first time and is especially useful to practicing programmers who use the book as a reference.
“Double Indexing” of All C++ Live-Code Examples
C++ How to Program, 5/e has 260 live-code examples and 849 exercises (including separate parts). We have double indexed each of the live-code examples and most of the more substantial exercises. For every source-code program in the book, we indexed the figure caption both alphabetically and as a subindex item under “Examples.” This makes it easier to find examples using particular features. The more substantial exercises are also indexed both alphabetically and as subindex items under “Exercises.”
Tour of the Book
In this section, we take a tour of the many capabilities of C++ you will study in C++ How to Program, 5/e. Figure 1 illustrates the dependencies among the chapters. We recommend studying these topics in the order indicated by the arrows, though other orders are possible. This book is widely used in all levels of C++ programming courses. Search the Web for “syllabus,” “C++” and “Deitel” to find syllabi used with recent editions of this book.
Chapter 1—Introduction to Computers, the Internet and World Wide Web—discusses what computers are, how they work and how they are programmed. The chapter gives a brief history of the development of programming languages from machine languages to assembly languages and high-level languages. The origin of the C++ programming language is discussed. Our free Dive-Into Series publications for other platforms are available at www.deitel.com/books/downloads.html. The chapter includes an introduction to a typical C++ programming environment. We walk readers through a “test drive” of a typical C++ application on Windows and Linux platforms. This chapter also introduces basic object technology concepts and terminology and the Unified Modeling Language.
Chapter 2—Introduction to C++ Programming—provides a lightweight introduction to programming applications in the C++ programming language. The chapter introduces nonprogrammers to basic programming concepts and constructs. The programs in this chapter illustrate how to display data on the screen and how to obtain data from the user at the keyboard. Chapter 2 ends with detailed treatments of decision making and arithmetic operations.
Chapter 3—Introduction to Classes and Objects—is the “featured” chapter for the new edition. It provides a friendly early introduction to classes and objects. Carefully developed and completely new in this edition, Chapter 3 gets students working with object orientation comfortably from the start. It was developed with the guidance of a distinguished team of industry and academic reviewers. We introduce classes, objects, member functions, constructors and data members using a series of simple real-world examples. We develop a well-engineered framework for organizing object-oriented programs in C++. First, we motivate the notion of classes with a simple example. Then we present a carefully paced sequence of seven complete working programs to demonstrate creating and using your own classes. These examples begin our integrated case study on developing a grade-book class that instructors can use to maintain student test scores. This case study is enhanced over the next several chapters, culminating with the version presented in Chapter 7, Arrays and Vectors. The GradeBook class case study describes how to define a class and how to use it to create an object. The case study discusses how to declare and define member functions to implement the class’s behaviors, how to declare data members to implement the class’s attributes and how to call an object’s member functions to make them perform their tasks. We introduce C++ Standard Library class string and create string objects to store the name of the course that a GradeBook object represents. Chapter 3 explains the differences between data members of a class and local variables of a function and how to use a constructor to ensure that an object’s data is initialized when the object is created. We show how to promote software reusability by separating a class definition from the client code (e.g., function main) that uses the class. We also introduce another fundamental principle of good software engineering—separating interface from implementation. The chapter includes a detailed diagram and discussion explaining the compilation and linking process that produces an executable application.
Chapter 4—Control Statements: Part 1—focuses on the program-development process involved in creating useful classes. The chapter discusses how to take a problem statement and develop a working C++ program from it, including performing intermediate steps in pseudocode. The chapter introduces some simple control statements for decision making (if and if else) and repetition (while). We examine counter-controlled and sentinel-controlled repetition using the GradeBook class from Chapter 3, and introduce C++’s increment, decrement and assignment operators. The chapter includes two enhanced versions of the GradeBook class, each based on Chapter 3’s final version. These versions each include a member function that uses control statements to calculate the average of a set of student grades. In the first version, the member function uses counter-controlled repetition to input 10 student grades from the user, then determines the average grade. In the second version, the member function uses sentinel-controlled repetition to input an arbitrary number of grades from the user, then calculates the average of the grades that were entered. The chapter uses simple UML activity diagrams to show the flow of control through each of the control statements.
Chapter 5—Control Statements: Part 2—continues the discussion of C++ control statements with examples of the for repetition statement, the do...while repetition statement, the switch selection statement, the break statement and the continue statement. We create an enhanced version of class GradeBook that uses a switch statement to count the number of A, B, C, D and F grades entered by the user. This version uses sentinel-controlled repetition to input the grades. While reading the grades from the user, a member function modifies data members that keep track of the count of grades in each letter grade category. Another member function of the class then uses these data members to display a summary report based on the grades entered. The chapter includes a discussion of logical operators.
Chapter 6—Functions and an Introduction to Recursion—takes a deeper look inside objects and their member functions. We discuss C++ Standard-Library functions and examine more closely how students can build their own functions. The techniques presented in Chapter 6 are essential to the production of properly organized programs, especially the kinds of larger programs and software that system programmers and application programmers are likely to develop in real-world applications. The “divide and conquer” strategy is presented as an effective means for solving complex problems by dividing them into simpler interacting components. The chapter’s first example continues the GradeBook class case study with an example of a function with multiple parameters. Students will enjoy the chapter’s treatment of random numbers and simulation, and the discussion of the dice game of craps, which makes elegant use of control statements. The chapter discusses the so-called “C++ enhancements to C,” including inline functions, reference parameters, default arguments, the unary scope resolution operator, function overloading and function templates. We also present C++’s call-by-value and call-by-reference capabilities. The header files table introduces many of the header files that the reader will use throughout the book. In this new edition, we provide a detailed discussion (with illustrations) of the function call stack and activation records to explain how C++ is able to keep track of which function is currently executing, how automatic variables of functions are maintained in memory and how a function knows where to return after it completes execution. The chapter then offers a solid introduction to recursion and includes a table summarizing the recursion examples and exercises distributed throughout the remainder of the book. Some texts leave recursion for a chapter late in the book; we feel this topic is best covered gradually throughout the text. The extensive collection of exercises at the end of the chapter includes several classic recursion problems, including the Towers of Hanoi.
Chapter 7—Arrays and Vectors—explains how to process lists and tables of values. We discuss the structuring of data in arrays of data items of the same type and demonstrate how arrays facilitate the tasks performed by objects. The early parts of this chapter use C-style, pointer-based arrays, which, as you will see in Chapter 8, are really pointers to the array contents in memory. We then present arrays as full-fledged objects in the last section of the chapter, where we introduce the C++ Standard Library vector class template—a robust array data structure. The chapter presents numerous examples of both one-dimensional arrays and two-dimensional arrays. Examples in the chapter investigate various common array manipulations, printing bar charts, sorting data and passing arrays to functions. The chapter includes the final two GradeBook case study sections, in which we use arrays to store student grades for the duration of a program’s execution. Previous versions of the class process a set of grades entered by the user, but do not maintain the individual grade values in data members of the class. In this chapter, we use arrays to enable an object of the GradeBook class to maintain a set of grades in memory, thus eliminating the need to repeatedly input the same set of grades. The first version of the class stores the grades in a one-dimensional array and can produce a report containing the average of the grades, the minimum and maximum grades and a bar chart representing the grade distribution. The second version (i.e., the final version in the case study) uses a two-dimensional array to store the grades of a number of students on multiple exams in a semester. This version can calculate each student’s semester average, as well as the minimum and maximum grades across all grades received for the semester. The class also produces a bar chart displaying the overall grade distribution for the semester. Another key feature of this chapter is the discussion of elementary sorting and searching techniques. The end-of-chapter exercises include a variety of interesting and challenging problems, such as improved sorting techniques, the design of a simple airline reservations system, an introduction to the concept of turtle graphics (made famous in the LOGO language) and the Knight’s Tour and Eight Queens problems that introduce the notion of heuristic programming widely employed in the field of artificial intelligence. The exercises conclude with many recursion problems including selection sort, palindromes, linear search, the Eight Queens, printing an array, printing a string backwards and finding the minimum value in an array.
Chapter 8—Pointers and Pointer-Based Strings—presents one of the most powerful features of the C++ language—pointers. The chapter provides detailed explanations of pointer operators, call by reference, pointer expressions, pointer arithmetic, the relationship between pointers and arrays, arrays of pointers and pointers to functions. We demonstrate how to use const with pointers to enforce the principle of least privilege to build more robust software. We also introduce and using the sizeof operator to determine the size of a data type or data items in bytes during program compilation. There is an intimate relationship between pointers, arrays and C-style strings in C++, so we introduce basic C-style string-manipulation concepts and discuss some of the most popular C-style string-handling functions, such as getline (input a line of text), strcpy and strncpy (copy a string), strcat and strncat (concatenate two strings), strcmp and strncmp (compare two strings), strtok (“tokenize” a string into its pieces) and strlen (return the length of a string). In this new edition, we use string objects (introduced in Chapter 3) in place of C-style, char * pointer-based strings wherever possible. However, we include char * strings in Chapter 8 to help the reader master pointers and prepare for the professional world in which the reader will see a great deal of C legacy code that has been implemented over the last three decades. Thus, the reader will become familiar with the two most prevalent methods of creating and manipulating strings in C++. Many people find that the topic of pointers is, by far, the most difficult part of an introductory programming course. In C and “raw C++” arrays and strings are pointers to array and string contents in memory (even function names are pointers). Studying this chapter carefully should reward you with a deep understanding of pointers. The chapter is loaded with challenging exercises. The chapter exercises include a simulation of the classic race between the tortoise and the hare, card-shuffling and dealing algorithms, recursive quicksort and recursive maze traversals. A special section entitled Building Your Own Computer also is included. This section explains machine-language programming and proceeds with a project involving the design and implementation of a computer simulator that leads the student to write and run machine-language programs. This unique feature of the text will be especially useful to the reader who wants to understand how computers really work. Our students enjoy this project and often implement substantial enhancements, many of which are suggested in the exercises. A second special section includes challenging string-manipulation exercises related to text analysis, word processing, printing dates in various formats, check protection, writing the word equivalent of a check amount, Morse Code and metric-to-English conversions.
Chapter 9—Classes: A Deeper Look, Part 1—continues our discussion of object-oriented programming. This chapter uses a rich Time class case study to illustrate accessing class members, separating interface from implementation, using access functions and utility functions, initializing objects with constructors, destroying objects with destructors, assignment by default memberwise copy and software reusability. Students learn the order in which constructors and destructors are called during the lifetime of an object. A modification of the Time case study demonstrates the problems that can occur when a member function returns a reference to a private data member, which breaks the encapsulation of the class. The chapter exercises challenge the student to develop classes for times, dates, rectangles and playing tic-tac-toe. Students generally enjoy game-playing programs. Mathematically inclined readers will enjoy the exercises on creating class Complex (for complex numbers), class Rational (for rational numbers) and class HugeInteger (for arbitrarily large integers).
Chapter 10—Classes: A Deeper Look, Part 2—continues the study of classes and presents additional object-oriented programming concepts. The chapter discusses declaring and using constant objects, constant member functions, composition—the process of building classes that have objects of other classes as members, friend functions and friend classes that have special access rights to the private and protected members of classes, the this pointer, which enables an object to know its own address, dynamic memory allocation, static class members for containing and manipulating class-wide data, examples of popular abstract data types (arrays, strings and queues), container classes and iterators. In our discussion of const objects, we mention keyword mutable which is used in a subtle manner to enable modification of “non-visible” implementation in const objects. We discuss dynamic memory allocation using new and delete. When new fails, the program terminates by default because new “throws an exception” in standard C++. We motivate the discussion of static class members with a video-game-based example. We emphasize how important it is to hide implementation details from clients of a class; then, we discuss proxy classes, which provide a means of hiding implementation (including the private data in class headers) from clients of a class. The chapter exercises include developing a savings-account class and a class for holding sets of integers.
Chapter 11—Operator Overloading; String and Array Objects—presents one of the most popular topics in our C++ courses. Students really enjoy this material. They find it a perfect match with the detailed discussion of crafting valuable classes in Chapters 9 and 10. Operator overloading enables the programmer to tell the compiler how to use existing operators with objects of new types. C++ already knows how to use these operators with objects of built-in types, such as integers, floats and characters. But suppose that we create a new String class—what would the plus sign mean when used between String objects? Many programmers use plus (+) with strings to mean concatenation. In Chapter 11, the programmer will learn how to “overload” the plus sign, so when it is written between two String objects in an expression, the compiler will generate a function call to an “operator function” that will concatenate the two Strings. The chapter discusses the fundamentals of operator overloading, restrictions in operator overloading, overloading with class member functions vs. with nonmember functions, overloading unary and binary operators and converting between types. Chapter 11 features the collection of substantial case studies including an array class, a String class, a date class, a huge integer class and a complex numbers class (the last two appear with full source code in the exercises). Mathematically inclined students will enjoy creating the polynomial class in the exercises. This material is different from most programming languages and courses. Operator overloading is a complex topic, but an enriching one. Using operator overloading wisely helps you add extra “polish” to your classes. The discussions of class Array and class String are particularly valuable to students who have already used the C++ Standard Library string class and vector class template that provide similar capabilities. The exercises encourage the student to add operator overloading to classes Complex, Rational and HugeInteger to enable convenient manipulation of objects of these classes with operator symbols—as in mathematics—rather than with function calls as the student did in the Chapter 10 exercises.
Chapter 12—Object-Oriented Programming: Inheritance—introduces one of the most fundamental capabilities of object-oriented programming languages—inheritance: a form of software reusability in which new classes are developed quickly and easily by absorbing the capabilities of existing classes and adding appropriate new capabilities. In the context of an Employee hierarchy case study, this substantially revised chapter presents a five-example sequence demonstrating private data, protected data and good software engineering with inheritance. We begin by demonstrating a class with private data members and public member functions to manipulate that data. Next, we implement a second class with additional capabilities, intentionally and tediously duplicating much of the first example’s code. The third example begins our discussion of inheritance and software reuse—we use the class from the first example as a base class and quickly and simply inherit its data and functionality into a new derived class. This example introduces the inheritance mechanism and demonstrates that a derived class cannot access its base class’s private members directly. This motivates our fourth example, in which we introduce protected data in the base class and demonstrate that the derived class can indeed access the protected data inherited from the base class. The last example in the sequence demonstrates proper software engineering by defining the base class’s data as private and using the base class’s public member functions (that were inherited by the derived class) to manipulate the base class’s private data in the derived class. The chapter discusses the notions of base classes and derived classes, protected members, public inheritance, protected inheritance, private inheritance, direct base classes, indirect base classes, constructors and destructors in base classes and derived classes, and software engineering with inheritance. The chapter also compares inheritance (the “is-a” relationship) with composition (the “has-a” relationship) and introduces the “uses-a” and “knows-a” relationships.
Chapter 13—Object-Oriented Programming: Polymorphism—deals with another fundamental capability of object-oriented programming: polymorphic behavior. The completely revised Chapter 13 builds on the inheritance concepts presented in Chapter 12 and focuses on the relationships among classes in a class hierarchy and the powerful processing capabilities that these relationships enable. When many classes are related to a common base class through inheritance, each derived-class object may be treated as a base-class object. This enables programs to be written in a simple and general manner independent of the specific types of the derived-class objects. New kinds of objects can be handled by the same program, thus making systems more extensible. Polymorphism enables programs to eliminate complex switch logic in favor of simpler “straight-line” logic. A screen manager of a video game, for example, can send a draw message to every object in a linked list of objects to be drawn. Each object knows how to draw itself. An object of a new class can be added to the program without modifying that program (as long as that new object also knows how to draw itself). The chapter discusses the mechanics of achieving polymorphic behavior via virtual functions. It distinguishes between abstract classes (from which objects cannot be instantiated) and concrete classes (from which objects can be instantiated). Abstract classes are useful for providing an inheritable interface to classes throughout the hierarchy. We demonstrate abstract classes and polymorphic behavior by revisiting the Employee hierarchy of Chapter 12. We introduce an abstract Employee base class, from which classes CommissionEmployee, HourlyEmployee and SalariedEmployee inherit directly and class BasePlusCommissionEmployee inherits indirectly. In the past, our professional clients have insisted that we provide a deeper explanation that shows precisely how polymorphism is implemented in C++, and hence, precisely what execution time and memory “costs” are incurred when programming with this powerful capability. We responded by developing an illustration and a precise explanation of the vtables (virtual function tables) that the C++ compiler builds automatically to support polymorphism. To conclude, we introduce run-time type information (RTTI) and dynamic casting, which enable a program to determine an object’s type at execution time, then act on that object accordingly. Using RTTI and dynamic casting, we give a 10% pay increase to employees of a specific type, then calculate the earnings for such employees. For all other employee types, we calculate their earnings polymorphically.
Chapter 14—Templates—discusses one of C++’s more powerful software reuse features, namely templates. Function templates and class templates enable programmers to specify, with a single code segment, an entire range of related overloaded functions (called function template specializations) or an entire range of related classes (called class-template specializations). This technique is called generic programming. Function templates were introduced in Chapter 6. This chapter presents additional discussions and examples on function template. We might write a single class template for a stack class, then have C++ generate separate class-template specializations, such as a “stack-of-int” class, a “stack-of-float” class, a “stack-of-string” class and so on. The chapter discusses using type parameters, nontype parameters and default types for class templates. We also discuss the relationships between templates and other C++ features, such as overloading, inheritance, friends and static members. The exercises challenge the student to write a variety of function templates and class templates and to employ these in complete programs. We greatly enhance the treatment of templates in our discussion of the Standard Template Library (STL) containers, iterators and algorithms in Chapter 23.
Chapter 15—C++ Stream Input/Output—contains a comprehensive treatment of standard C++ input/output capabilities. This chapter discusses a range of capabilities sufficient for performing most common I/O operations and overviews the remaining capabilities. Many of the I/O features are object oriented. This style of I/O makes use of other C++ features, such as references, function overloading and operator overloading. The various I/O capabilities of C++, including output with the stream insertion operator, input with the stream extraction operator, type-safe I/O, formatted I/O, unformatted I/O (for performance). Users can specify how to perform I/O for objects of user-defined types by overloading the stream insertion operator (<<) and the stream extraction operator (>>). This extensibility is one of C++’s most valuable features. C++ provides various stream manipulators that perform formatting tasks. This chapter discusses stream manipulators that provide capabilities such as displaying integers in various bases, controlling floating-point precision, setting field widths, displaying decimal point and trailing zeros, justifying output, setting and unsetting format state, setting the fill character in fields. We also present an example that creates user-defined output stream manipulators.
Chapter 16—Exception Handling—discusses how exception handling enables programmers to write programs that are robust, fault tolerant and appropriate for business-critical and mission-critical environments. The chapter discusses when exception handling is appropriate; introduces the basic capabilities of exception handling with try blocks, throw statements and catch handlers; indicates how and when to rethrow an exception; explains how to write an exception specification and process unexpected exceptions; and discusses the important ties between exceptions and constructors, destructors and inheritance. The exercises in this chapter show the student the diversity and power of C++’s exception-handling capabilities. We discuss rethrowing an exception, and we illustrate how new can fail when memory is exhausted. Many older C++ compilers return 0 by default when new fails. We show the new style of new failing by throwing a bad_alloc (bad allocation) exception. We illustrate how to use function set_new_handler to specify a custom function to be called to deal with memory-exhaustion situations. We discuss how to use the auto_ptr class template to delete dynamically allocated memory implicitly, thus avoiding memory leaks. To conclude this chapter, we present the Standard Library exception hierarchy.
Chapter 17—File Processing—discusses techniques for creating and processing both sequential files and random-access files. The chapter begins with an introduction to the data hierarchy from bits, to bytes, to fields, to records and to files. Next, we present the C++ view of files and streams. We discuss sequential files and build programs that show how to open and close files, how to store data sequentially in a file and how to read data sequentially from a file. We then discuss random-access files and build programs that show how to create a file for random access, how to read and write data to a file with random access and how to read data sequentially from a randomly accessed file. The case study combines the techniques of accessing files both sequentially and randomly into a complete transaction-processing program. Students in our industry seminars have mentioned that, after studying the material on file processing, they were able to produce substantial file-processing programs that were immediately useful in their organizations. The exercises ask the student to implement a variety of programs that build and process both sequential files and random-access files.
Chapter 18—Class string and String Stream Processing—The chapter discusses C++’s capabilities for inputting data from strings in memory and outputting data to strings in memory; these capabilities often are referred to as in-core formatting or string-stream processing. Class string is a required component of the Standard Library. We preserved the treatment of C-like, pointer-based strings in Chapter 8 and later for several reasons. First, it strengthens the reader’s understanding of pointers. Second, for the next decade or so, C++ programmers will need to be able to read and modify the enormous amounts of C legacy code that has accumulated over the last quarter of a century—this code processes strings as pointers, as does a large portion of the C++ code that has been written in industry over the last many years. In Chapter 18 we discuss string assignment, concatenation and comparison. We show how to determine various string characteristics such as a string’s size, capacity and whether or not it is empty. We discuss how to resize a string. We consider the various “find” functions that enable us to find a substring in a string (searching the string either forwards or backwards), and we show how to find either the first occurrence or last occurrence of a character selected from a string of characters, and how to find the first occurrence or last occurrence of a character that is not in a selected string of characters. We show how to replace, erase and insert characters in a string and how to convert a string object to a C-style char * string.
Chapter 19—Web Programming—This optional chapter has everything you need to begin developing your own Web-based applications that will really run on the Internet! You will learn how to build so-called n-tier applications, in which the functionality provided by each tier can be distributed to separate computers across the Internet or executed on the same computer. In particular, we build a three-tier online bookstore application. The bookstore’s information is stored in the application’s bottom tier, also called the data tier. In industrial-strength applications, the data tier is typically a database such as Oracle, Microsoft SQL Server or MySQL. For simplicity, we use text files and employ the file-processing techniques of Chapter 17 to access and modify these files. The user enters requests and receives responses at the application’s top tier, also called the user-interface tier or the client tier, which is typically a computer running a popular Web browser such as Microsoft Internet Explorer, Mac OS X Safari , Mozilla Firefox, Opera or Netscape . Web browsers, of course, know how to communicate with Web sites throughout the Internet. The middle tier, also called the business-logic tier, contains both a Web server and an application-specific C++ program (e.g., our bookstore application). The Web server communicates with the C++ program (and vice versa) via the CGI (Common Gateway Interface) protocol. This program is referred to as a CGI script. We use the popular Apache HTTP server, which is available free for download from the Apache Web site, www.apache.org. Apache installation instructions for many popular platforms, including Linux and Windows systems, are available at that site and at www.deitel.com and www.prenhall.com/deitel. The Web server knows how to talk to the client tier across the Internet using a protocol called HTTP (Hypertext Transfer Protocol). We discuss the two most popular HTTP methods for sending data to a Web server—GET and POST. We then discuss the crucial role of the Web server in Web programming and provide a simple example that requests an Extensible HyperText Markup Language (XHTML) document from a Web server. We discuss CGI and how it allows a Web server to communicate with the top tier and CGI applications. We provide a simple example that gets the server’s time and renders it in a browser. Other examples demonstrate how to process form-based user input via the string processing techniques introduced in Chapter 18. In our forms-based examples we use buttons, password fields, check boxes and text fields. We present an example of an interactive portal for a travel company that displays airfares to various cities. Travel-club members can log in and view discounted airfares. We also discuss various methods of storing client-specific data, which include hidden fields (i.e., information stored in a Web page but not rendered by the Web browser) and cookies—small text files that the browser stores on the client’s machine. The chapter examples conclude with a case study of an online book store that allows users to add books to a shopping cart. This case study contains several CGI scripts that interact to form a complete application. The online book store is password protected, so users first must log in to gain access. The chapter’s Web resources include information about the CGI specification, C++ CGI libraries and Web sites related to the Apache HTTP server.
Chapter 20—Searching and Sorting—discusses two of the most important classes of algorithms in computer science. We consider a variety of specific algorithms for each and compare them with regard to their memory consumption and processor consumption (introducing Big O notation, which indicates how hard an algorithm may have to work to solve a problem). Searching data involves determining whether a value (referred to as the search key) is present in the data and, if so, finding the value’s location. In the examples and exercises of this chapter, we discuss a variety of searching algorithms, including: binary search and recursive versions of linear search and binary search. Through examples and exercises, Chapter 20 discusses the recursive merge sort, bubble sort, bucket sort and the recursive quicksort.
Chapter 21—Data Structures—discusses the techniques used to create and manipulate dynamic data structures. The chapter begins with discussions of self-referential classes and dynamic memory allocation, then proceeds with a discussion of how to create and maintain various dynamic data structures, including linked lists, queues (or waiting lines), stacks and trees. For each type of data structure, we present complete, working programs and show sample outputs. The chapter also helps the student master pointers. The chapter includes abundant examples that use indirection and double indirection—a particularly difficult concept. One problem when working with pointers is that students have trouble visualizing the data structures and how their nodes are linked together. We have included illustrations that show the links and the sequence in which they are created. The binary-tree example is a superb capstone for the study of pointers and dynamic data structures. This example creates a binary tree, enforces duplicate elimination and introduces recursive preorder, inorder and postorder tree traversals. Students have a genuine sense of accomplishment when they study and implement this example. They particularly appreciate seeing that the inorder traversal prints the node values in sorted order. We include a substantial collection of exercises. A highlight of the exercises is the special section Building Your Own Compiler. The exercises walk the student through the development of an infix-to-postfix-conversion program and a postfix-expression-evaluation program. We then modify the postfix-evaluation algorithm to generate machine-language code. The compiler places this code in a file (using the techniques of Chapter 17. Students then run the machine language produced by their compilers on the software simulators they built in the exercises of Chapter 8! The 35 exercises include recursively searching a list, recursively printing a list backwards, binary-tree node deletion, level-order traversal of a binary tree, printing trees, writing a portion of an optimizing compiler, writing an interpreter, inserting/deleting anywhere in a linked list, implementing lists and queues without tail pointers, analyzing the performance of binary-tree searching and sorting, implementing an indexed-list class and a supermarket simulation that uses queueing. After studying Chapter 21, the reader is prepared for the treatment of STL containers, iterators and algorithms in Chapter 23. The STL containers are prepackaged, templatized data structures that most programmers will find sufficient for the vast majority of applications they will need to implement. The STL is a giant leap forward in achieving the vision of reuse.
Chapter 22—Bits, Characters, Strings and Structures—presents a variety of important features. This chapter begins by comparing C++ structures to classes then defining and using C-like structures. We show how to declare structures, initialize structures and pass structures to functions. The chapter features a high-performance card-shuffling and dealing simulation. This is an excellent opportunity for the instructor to emphasize the quality of algorithms. C++’s powerful bit-manipulation capabilities enable programmers to write programs that exercise lower-level hardware capabilities. This helps programs process bit strings, set individual bits and store information more compactly. Such capabilities, often found only in low-level assembly languages, are valued by programmers writing system software, such as operating systems and networking software. As you recall, we introduced C-style char * string manipulation in Chapter 8 and presented the most popular string-manipulation functions. In Chapter 22, we continue our presentation of characters and C-style char * strings. We present the various character-manipulation capabilities of the <cctype> library—such as the ability to test a character to determine whether it is a digit, an alphabetic character, an alphanumeric character, a hexadecimal digit, a lowercase letter or an uppercase letter. We present the remaining string-manipulation functions of the various string-related libraries; as always, every function is presented in the context of a complete, working C++ program. The 32 exercises encourage the student to try out most of the capabilities discussed in the chapter. The feature exercise leads the student through the development of a spelling-checker program. This chapter presents a deeper treatment of C-like, char * strings for the benefit of C++ programmers who are likely to work with C legacy code.
Chapter 23—Standard Template Library (STL)—Throughout this book, we discuss the importance of software reuse. Recognizing that many data structures and algorithms are commonly used by C++ programmers, the C++ standard committee added the Standard Template Library (STL) to the C++ Standard Library. The STL defines powerful, template-based, reusable components that implement many common data structures and algorithms used to process those data structures. The STL offers proof of concept for generic programming with templates—introduced in Chapter 14 and demonstrated in detail in Chapter 21. This chapter introduces the STL and discusses its three key components—containers (popular templatized data structures), iterators and algorithms. The STL containers are data structures capable of storing objects of any data type. We will see that there are three container categories—first-class containers, adapters and near containers. STL iterators, which have similar properties to those of pointers, are used by programs to manipulate the STL-container elements. In fact, standard arrays can be manipulated as STL containers, using standard pointers as iterators. We will see that manipulating containers with iterators is convenient and provides tremendous expressive power when combined with STL algorithms—in some cases, reducing many lines of code to a single statement. STL algorithms are functions that perform common data manipulations such as searching, sorting and comparing elements (or entire containers). There are approximately 70 algorithms implemented in the STL. Most of these use iterators to access container elements. We will see that each first-class container supports specific iterator types, some of which are more powerful than others. A container’s supported iterator type determines whether the container can be used with a specific algorithm. Iterators encapsulate the mechanism used to access container elements. This encapsulation enables many of the STL algorithms to be applied to several containers without regard for the underlying container implementation. As long as a container’s iterators support the minimum requirements of the algorithm, then the algorithm can process that container’s elements. This also enables programmers to create algorithms that can process the elements of multiple different container types. Chapter 21 discusses how to implement data structures with pointers, classes and dynamic memory. Pointer-based code is complex, and the slightest omission or oversight can lead to serious memory-access violations and memory-leak errors with no compiler complaints. Implementing additional data structures such as deques, priority queues, sets, maps, etc. requires substantial additional work. In addition, if many programmers on a large project implement similar containers and algorithms for different tasks, the code becomes difficult to modify, maintain and debug. An advantage of the STL is that programmers can reuse the STL containers, iterators and algorithms to implement common data representations and manipulations. This reuse results in substantial development-time and resource savings. This is a friendly, accessible chapter that should convince you of the value of the STL and encourage further study.
Chapter 24—Other Topics—is a collection of miscellaneous C++ topics. This chapter discusses one additional cast operator—const_cast. This operator, along with static_cast (Chapter 5), dynamic_cast (Chapter 13) and reinterpret_cast (Chapter 17), provide a more robust mechanism for converting between types than do the original cast operators C++ inherited from C (which are now deprecated). We discuss namespaces, a feature particularly crucial for software developers who build substantial systems, especially for those who build systems from class libraries. Namespaces prevent naming collisions, which can hinder such large software efforts. The Chapter discusses the operator keywords, which are useful for programmers who have keyboards that do not support certain characters used in operator symbols, such as !, &, ^, ~ and |. These operators can also be used by programmers who do not like cryptic operator symbols. We discuss keyword mutable, which allows a member of a const object to be changed. Previously, this was accomplished by “casting away const-ness”, which is considered a dangerous practice. We also discuss pointer-to-member operators .* and ->*, multiple inheritance (including the problem of “diamond inheritance”) and virtual base classes.
Appendix A—Operator Precedence and Associativity Chart—presents the complete set of C++ operator symbols, in which each operator appears on a line by itself with its operator symbol, its name and its associativity.
Appendix B—ASCII Character Set—All the programs in this book use the ASCII character set, which is presented in this appendix.
Appendix C—Fundamental Types—lists all fundamental types defined in the C++ Standard.
Appendix D—Number Systems—discusses the binary, octal, decimal and hexadecimal number systems. It considers how to convert numbers between bases and explains the one’s complement and two’s complement binary representations.
Appendix E—C Legacy-Code Topics—presents additional topics including several advanced topics not ordinarily covered in introductory courses. We show how to redirect program input to come from a file, redirect program output to be placed in a file, redirect the output of one program to be the input of another program (piping) and append the output of a program to an existing file. We develop functions that use variable-length argument lists and show how to pass command-line arguments to function main and use them in a program. We discuss how to compile programs whose components are spread across multiple files, register functions with atexit to be executed at program termination and terminate program execution with function exit. We also discuss the const and volatile type qualifiers, specifying the type of a numeric constant using the integer and floating-point suffixes, using the signal-handling library to trap unexpected events, creating and using dynamic arrays with calloc and realloc, using unions as a space-saving technique and using linkage specifications when C++ programs are to be linked with legacy C code. As the title suggests, this chapter is intended primarily for C++ programmers who will be working with C legacy code as most C++ programmers are almost certain to do at one point in their careers.
Appendix F—Preprocessor—provides detailed discussions of the preprocessor directives. The chapter includes more complete information on the #include directive, which causes a copy of a specified file to be included in place of the directive before the file is compiled and the #define directive that creates symbolic constants and macros. The chapter explains conditional compilation for enabling the programmer to control the execution of preprocessor directives and the compilation of program code. The # operator that converts its operand to a string and the ## operator that concatenates two tokens are discussed. The various predefined preprocessor symbolic constants (__LINE__, __FILE__, __DATE__, __STDC__, __TIME__ and __TIMESTAMP__) are presented. Finally, macro assert of the header file <cassert> is discussed, which is valuable in program testing, debugging, verification and validation.
Appendix G—ATM Case Study Code—contains the implementation of our case study on object-oriented design with the UML. This appendix is discussed in the overview of the case study (presented shortly).
Appendix H—UML 2 Diagrams—Overviews the UML 2 diagram types that are not found in the OOD/UML Case Study.
Appendix I—C++ Internet and Web Resources—contains a listing of valuable C++ resources, such as demos, information about popular compilers (including “freebies”), books, articles, conferences, job banks, journals, magazines, help, tutorials, FAQs (frequently asked questions), newsgroups, Web-based courses, product news and C++ development tools.
Appendix J—Introduction to XHTML—provides an introduction to XHTML—a markup language for describing the elements of a Web page so that a browser, such as Microsoft Internet Explorer or Netscape, can render that page. The reader should be familiar with the contents of this appendix before studying Chapter 16, Web Programming with CGI. This appendix does not contain any C++ programming. Some key topics covered include incorporating text and images into an XHTML document, linking to other XHTML documents, incorporating special characters (such as copyright and trademark symbols) into an XHTML document, separating parts of an XHTML document with horizontal lines (called horizontal rules), presenting information in lists and tables, and collecting information from users browsing a site.
Appendix K—XHTML Special Characters—lists many commonly used XHTML special characters, called character entity references.
Appendix L—Using the Visual C++ .NET Debugger—demonstrates key features of the Visual Studio .NET Debugger, which allows a programmer to monitor the execution of applications to locate and remove logic errors. The appendix presents step-by-step instructions, so students learn how to use the debugger in a hands-on manner.
Appendix M—Using the GNU C++ Debugger—demonstrates key features of the GNU C++ Debugger, which allows a programmer to monitor the execution of applications to locate and remove logic errors. The appendix presents step-by-step instructions, so students learn how to use the debugger in a hands-on manner.
Bibliography—lists over 100 books and articles to encourage the student to do further reading on C++ and OOP.
Index—The comprehensive index enables the reader to locate by keyword any term or concept throughout the text.
Object-Oriented Design of an ATM with the UML:
A Tour of the Optional Software Engineering Case Study
In this section we tour the book’s optional case study of object-oriented design with the UML. This tour previews the contents of the nine Software Engineering Case Study sections (in Chapters 1–7, 9 and 13). After completing this case study, the reader will be thoroughly familiar with a carefully reviewed object-oriented design and implementation for a significant C++ application.
The design presented in the ATM case study was developed at Deitel & Associates, Inc. and scrutinized by a distinguished developmental review team of industry professionals and academics. We crafted this design to meet the requirements of introductory course sequences. Real ATM systems used by banks and their customers worldwide are based on more sophisticated designs that take into consideration many more issues than we have addressed here. Our primary goal throughout the design process was to create a simple design that would be clear to OOD and UML novices, while still demonstrating key OOD concepts and the related UML modeling techniques. We worked hard to keep the design and the code relatively small so that it would work well in the introductory course sequence.
Section 1.17—Software Engineering Case Study: Introduction to Object Technology and the UML—introduces the object-oriented design case study with the UML. The section introduces the basic concepts and terminology of object technology, including classes, objects, encapsulation, inheritance and polymorphism. We discuss the history of the UML. This is the only required section of the case study.
Section 2.8—(Optional) Software Engineering Case Study: Examining the ATM Requirements Document—discusses a requirements document that specifies the requirements for a system that we will design and implement—the software for a simple automated teller machine (ATM). We investigate the structure and behavior of object-oriented systems in general. We discuss how the UML will facilitate the design process in subsequent Software Engineering Case Study sections by providing several additional types of diagrams to model our system. We include a list of URLs and book references on object-oriented design with the UML. We discuss the interaction between the ATM system specified by the requirements document and its user. Specifically, we investigate the scenarios that may occur between the user and the system itself—these are called use cases. We model these interactions, using use case diagrams of the UML.
Section 3.11—(Optional) Software Engineering Case Study: Identifying the Classes in the ATM Requirements Documents—begins to design the ATM system. We identify its classes, or “building blocks,” by extracting the nouns and noun phrases from the requirements document. We arrange these classes into a UML class diagram that describes the class structure of our simulation. The class diagram also describes relationships, known as associations, among classes.
Section 4.13—(Optional) Software Engineering Case Study: Identifying Class Attributes in the ATM System—focuses on the attributes of the classes discussed in Section 3.11. A class contains both attributes (data) and operations (behaviors). As we will see in later sections, changes in an object’s attributes often affect the object’s behavior. To determine the attributes for the classes in our case study, we extract the adjectives describing the nouns and noun phrases (which defined our classes) from the requirements document, then place the attributes in the class diagram we created in Section 3.11.
Section 5.11—(Optional) Software Engineering Case Study: Identifying Objects’ States and Activities in the ATM System—discusses how an object, at any given time, occupies a specific condition called a state. A state transition occurs when that object receives a message to change state. The UML provides the state machine diagram, which identifies the set of possible states that an object may occupy and models that object’s state transitions. An object also has an activity—the work it performs in its lifetime. The UML provides the activity diagram—a flowchart that models an object’s activity. In this section, we use both types of diagrams to begin modeling specific behavioral aspects of our ATM system, such as how the ATM carries out a withdrawal transaction and how the ATM responds when the user is authenticated.
Section 6.22—(Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System—identifies the operations, or services, of our classes. We extract from the requirements document the verbs and verb phrases that specify the operations for each class. We then modify the class diagram of Section 3.11 to include each operation with its associated class. At this point in the case study, we will have gathered all information possible from the requirements document. However, as future chapters introduce such topics as inheritance, we will modify our classes and diagrams.
Section 7.12—(Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System—provides a “rough sketch” of the model for our ATM system. In this section, we see how it works. We investigate the behavior of the simulation by discussing collaborations—messages that objects send to each other to communicate. The class operations that we discovered in Section 6.22 turn out to be the collaborations among the objects in our system. We determine the collaborations, then collect them into a communication diagram—the UML diagram for modeling collaborations. This diagram reveals which objects collaborate and when. We present a communication diagram of the collaborations among objects to perform an ATM balance inquiry. We then present the UML sequence diagram for modeling interactions in a system. This diagram emphasizes the chronological ordering of messages. A sequence diagram models how objects in the system interact to carry out withdrawal and deposit transactions.
Section 9.12—(Optional) Software Engineering Case Study: Starting to Program the Classes of the ATM System—takes a break from designing the behavior of our system. We begin the implementation process to emphasize the material discussed in Chapter 9. Using the UML class diagram of Section 3.11 and the attributes and operations discussed in Section 4.13 and Section 6.22, we show how to implement a class in C++ from a design. We do not implement all classes—because we have not completed the design process. Working from our UML diagrams, we create code for the Withdrawal class.
Section 13.10—(Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System—continues our discussion of object-oriented programming. We consider inheritance—classes sharing common characteristics may inherit attributes and operations from a “base” class. In this section, we investigate how our ATM system can benefit from using inheritance. We document our discoveries in a class diagram that models inheritance relationships—the UML refers to these relationships as generalizations. We modify the class diagram of Section 3.11 by using inheritance to group classes with similar characteristics. This section concludes the design of the model portion of our simulation. We fully implement this model in 877 lines of C++ code in Appendix G.
Appendix G—ATM Case Study Code—The majority of the case study involves designing the model (i.e., the data and logic) of the ATM system. In this appendix, we implement that model in C++. Using all the UML diagrams we created, we present the C++ classes necessary to implement the model. We apply the concepts of object-oriented design with the UML and object-oriented programming in C++ that you learned in the chapters. By the end of this appendix, students will have completed the design and implementation of a real-world system, and should feel confident tackling larger systems, such as those that professional software engineers build.
Appendix H—UML 2 Additional Diagrams—Overviews the UML 2 diagram types that are not found in the OOD/UML Case Study.
Software Bundled with C++ How to Program, 5/e
For the academic educational market only, this textbook is available in a value pack with Microsoft Visual C++ .NET 2003 Standard Edition integrated development environment as a free supplement. There is no time limit for using the software. [Note: If you are a professional using this publication, you will have to either purchase the necessary software to build and run the applications in this textbook or download one of the many free compilers available online.][Note: If you are a student in a course for which this book is the required textbook, you must purchase your book from your college bookstore to ensure that you get the value pack with the software. College bookstores will need to order the books directly from Prentice Hall to get the value pack with the software. A caution—used books may not include the software.]
Free C++ Compilers and Trial-Edition C++ Compilers on the Web
Many C++ compilers are available for download from the Web. We discuss several that are available for free or as free-trial versions. Please keep in mind that in many cases, the trial-edition software cannot be used after the (often brief) trial period has expired.
One popular organization that develops free software is the GNU Project (www.gnu.org), originally created to develop a free operating system similar to UNIX. GNU offers developer resources, including editors, debuggers and compilers. Many developers use the GCC (GNU Compiler Collection) compilers, available for download from gcc.gnu.org. The GCC contains compilers for C, C++, Java and other languages. The GCC compiler is a command-line compiler (i.e., it does not provide a graphical user interface). Many Linux and UNIX systems come with the GCC compiler installed. Red Hat has developed Cygwin (www.cygwin.com), an emulator that allows developers to use UNIX commands on Windows. Cygwin includes the GCC compiler.
Borland provides a Windows-based C++ developer product called C++Builder (www.borland.com/cbuilder/cppcomp/index.html). The basic C++Builder compiler (a command-line compiler) is free for download. Borland also provides several versions of C++Builder that contain graphical user interfaces (GUIs). These GUIs are formally called integrated development environments (IDEs) and enable the developer to edit, debug and test programs quickly and conveniently. Using an IDE, many of the tasks that involved tedious commands can now be executed via menus and buttons. Some of these products are available on a free-trial basis. For more information on C++Builder, visit
For Linux developers, Borland provides the Borland Kylix development environment. The Borland Kylix Open Edition, which includes an IDE, can be downloaded from
Borland also provides C++BuilderX—a cross-platform integrated C++ development environment. The free Personal Edition is available from
The command-line compiler (version 5.6.4) that comes with C++BuilderX was one of several compilers we used to test the programs in this book. Many of the downloads available from Borland require users to register.
The Digital Mars C++ Compiler (www.digitalmars.com), is available for Windows and DOS, and includes tutorials and documentation. Readers can download a command-line or IDE version of the compiler. The DJGPP C/C++ development system is available for computers running DOS. DJGPP stands for DJ’s GNU Programming Platform, where DJ is for DJ Delorie, the creator of DJGPP. Information on DJGPP can be found at www.delorie.com/djgpp. Locations where the compiler can be downloaded at are provided at www.delorie.com/djgpp/getting.html.
For a list of other compilers that are available free for download, visit the following sites:
Warnings and Error Messages on Older C++ Compilers
The programs in this book are designed to be used with compilers that support standard C++. However, there are variations among compilers that may cause occasional warnings or errors. In addition, though the standard specifies various situations that require errors to be generated, it does not specify the messages that compilers should issue. Warnings and error messages vary among compilers—this is normal.
Some older C++ compilers, such as Microsoft Visual C++ 6, Borland C++ 5.5 and various earlier versions of GNU C++ generate error or warning messages in places where newer compilers do not. Although most of the examples in this book will work with these older compilers, there are a few examples that need minor modifications to work with older compilers. The Web site for this book (www.deitel.com/books/cpphtp5/index.html) lists the warnings and error messages that are produced by several older compilers and what, if anything, you can do to fix the warnings and errors.
Notes Regarding using Declarations and C Standard Library Functions
The C++ Standard Library includes the functions from the C Standard Library. According to the C++ standard document, the contents of the header files that come from the C Standard Library are part of the “std” namespace. Some compilers (old and new) generate error messages when using declarations are encountered for C functions. We will post a list of these issues at www.deitel.com/books/cpphtp5/index.html.
Dive-Into Series Tutorials for Popular C++ Environments
Our free Dive-Into Series publications, which are available with the resources for C++ How to Program, 5/e at www.deitel.com/books/downloads.html, help students and instructors familiarize themselves with various C++ development tools. These publications include:
• Dive-Into Microsoft Visual C++ 6
• Dive-Into Microsoft Visual C++ .NET
• Dive-Into Borland C++Builder Compiler (command-line version)
• Dive-Into Borland C++Builder Personal (IDE version)
• Dive-Into GNU C++ on Linux and Dive-Into GNU C++ via Cygwin on Windows (Cygwin is a UNIX emulator for Windows. It includes the GNU C++ compiler)
Each of these tutorials shows how to compile, execute and debug C++ applications in that particular compiler product. Many of these documents also provide step-by-step instructions with screenshots to help readers install the software. Each document overviews the compiler and its online documentation.
Teaching Resources for C++ How to Program, 5/e
C++ How to Program, 5/e, has extensive resources for instructors. The Instructor’s Resource CD (IRCD) contains the Solutions Manual with solutions to the vast majority of the end-of-chapter exercises, a Test Item File of multiple-choice questions (approximately two per book section) and PowerPoint slides containing all the code and figures in the text, plus bulleted items that summarize the key points in the text. Instructors can customize the slides. [Note: The IRCD is available only to instructors through their Prentice Hall representatives. To find your local sales representative, visit
If you need additional help or if you have any questions about the IRCD, please e-mail us at firstname.lastname@example.org. We will respond promptly.]
C++ Multimedia Cyber Classroom, 5/e, Online
C++ How to Program, 5/e and Small C++ How to Program, 5/e each include a free, Web-based interactive multimedia ancillary to the book—The C++ Multimedia Cyber Classroom, 5/e—available with new books purchased from Prentice Hall for fall 2005 classes. Our Web-based Cyber Classroom will include audio walkthroughs of code examples in the text, solutions to about half of the exercises in the book, a free lab manual and more. For more information about the new Web-based Cyber Classroom, please visit our Web site at www.deitel.com or sign up for the free Deitel Buzz Online e-mail newsletter at
Students who use our Cyber Classrooms tell us that they like the interactivity and that the Cyber Classroom is a powerful reference tool. Professors tell us that their students enjoy using the Cyber Classroom and consequently spend more time on the courses, mastering more of the material than in textbook-only courses. For a complete list of our current CD-ROM-based Cyber Classrooms, see the Deitel Series page at the beginning of this book, the product listing and ordering information at the end of this book, or visit www.deitel.com, www.prenhall.com/deitel or www.InformIT.com/deitel.
C++ in the Lab
C++ in the Lab: Lab Manual to Accompany C++ How to Program, 5/e, our free online lab manual, complements C++ How to Program, 5/e, and Small C++ How to Program, 5/e, with hands-on lab assignments designed to reinforce students’ comprehension of lecture material. C++ in the Lab will be available with new books purchased from Prentice Hall for fall 2005 classes. This lab manual is designed for closed laboratories—regularly scheduled classes supervised by an instructor. Closed laboratories provide an excellent learning environment, because students can use concepts presented in class to solve carefully designed lab problems. Instructors are better able to measure the students’ understanding of the material by monitoring the students’ progress in lab. This lab manual also can be used for open laboratories, homework and for self-study.
The lab manual chapters are divided into Prelab Activities, Lab Exercises and Postlab Activities. Each chapter contains objectives that introduce the lab’s key topics and an assignment checklist for students to mark which exercises the instructor has assigned.
Solutions to the lab manual’s Prelab Activities, Lab Exercises and Postlab Activities are available in electronic form. Instructors can obtain these materials from their regular Prentice Hall representatives; the solutions are not available to students.
Prelab Activities are intended to be completed by students after studying each chapter of Small C++ How to Program, 5/e. Prelab Activities test students’ understanding of the textbook material and prepare students for the programming exercises in the lab session. The exercises focus on important terminology and programming concepts and are effective for self-review. Prelab Activities include Matching Exercises, Fill-in-the-Blank Exercises, Short-Answer Questions, Programming-Output Exercises (determine what short code segments do without actually running the program) and Correct-the-Code Exercises (identify and correct all errors in short code segments).
The most important section in each chapter is the Lab Exercises. These teach students how to apply the material learned in C++ How to Program, 5/e, and prepare them for writing C++ programs. Each lab contains one or more lab exercises and a debugging problem. The Lab Exercises contain the following:
• Lab Objectives highlight specific concepts on which the lab exercise focuses.
• Problem Descriptions provide the details of the exercise and hints to help students implement the program.
• Sample Outputs illustrate the desired program behavior, which further clarifies the problem descriptions and aids the students with writing programs.
• Program Templates take complete C++ programs and replace key lines of code with comments describing the missing code.
• Problem-Solving Tips highlight key issues that students need to consider when solving the lab exercises.
• Follow-Up Questions and Activities ask students to modify solutions to the lab exercises, write new programs that are similar to their lab-exercise solutions or explain the implementation choices that were made when solving lab exercises.
• Debugging Problems consist of blocks of code that contain syntax errors and/or logic errors. These alert students to the types of errors they are likely to encounter while programming.
Professors typically assign Postlab Activities to reinforce key concepts or to provide students with more programming experience outside the lab. Postlab Activities test the students’ understanding of the Prelab and Lab Exercise material, and ask students to apply their knowledge to creating programs from scratch. The section provides two types of programming activities: coding exercises and programming challenges. Coding exercises are short and serve as review after the Prelab Activities and Lab Exercises have been completed. The coding exercises ask students to write programs or program segments using key concepts from the textbook. Programming Challenges allow students to apply their knowledge to substantial programming exercises. Hints, sample outputs and pseudocode are provided to aid students with these problems. Students who successfully complete the Programming Challenges for a chapter have mastered the chapter material. Answers to the programming challenges are available at www.deitel.com/books/downloads.html.
CourseCompassSM, WebCT and Blackboard
Selected content from the Deitels’ introductory programming language How to Program series textbooks, including C++ How to Program, 5/e, is available to integrate into various popular course management systems, including CourseCompass, Blackboard and WebCT. Course management systems help faculty create, manage and use sophisticated Web-based educational tools and programs. Instructors can save hours of inputting data by using the Deitel course-management-systems content. Blackboard, CourseCompass and WebCT offer:
• Features to create and customize an online course, such as areas to post course information (e.g., policies, syllabi, announcements, assignments, grades, performance evaluations and progress tracking), class and student management tools, a gradebook, reporting tools, page tracking, a calendar and assignments.
• Communication tools to help create and maintain interpersonal relationships between students and instructors, including chat rooms, whiteboards, document sharing, bulletin boards and private e-mail.
• Flexible testing tools that allow an instructor to create online quizzes and tests from questions directly linked to the text, and that grade and track results effectively. All tests can be inputted into the gradebook for efficient course management. WebCT also allows instructors to administer timed online quizzes.
• Support materials for instructors are available in print and online formats.
In addition to the types of tools found in Blackboard and WebCT, CourseCompass from Prentice Hall includes:
• CourseCompass course home page, which makes the course as easy to navigate as a book. An expandable table of contents allows instructors to view course content at a glance and to link to any section.
• Hosting on Prentice Hall’s centralized servers, which allows course administrators to avoid separate licensing fees or server-space issues. Access to Prentice Hall technical support is available.
• “How Do I” online-support sections are available for users who need help personalizing course sites, including step-by-step instructions for adding PowerPoint slides, video and more.
• Instructor Quick Start Guide helps instructors create online courses using a simple, step-by-step process.
To view free online demonstrations and learn more about these Course Management Systems, which support Deitel content, visit the following Web sites:
• Blackboard: www.blackboard.com and www.prenhall.com/blackboard
• WebCT: www.webct.com and www.prenhall.com/webct
• CourseCompass: www.coursecompass.com and
Today’s students have increasing demands on their time and money, and they need to be resourceful about how, when and where they study. Pearson/Prentice Hall, a division of Pearson Education, has responded to that need by creating PearsonChoices to allow faculty and students to choose from a variety of textbook formats and prices.
Small C++ How to Program, 5/e is our alternative print edition to C++ How to Program, 5/e. Small C++ How to Program, 5/e is a smaller text that is focused on Computer Science 1 (CS1) programming courses and is priced lower than our 24-chapter C++ How to Program, 5/e and other competing texts in the CS1 market.
Chapters in Both Small C++ How to Program, 5/e and C++ How to Program, 5/e
Chapter 1—Introduction to Computers, the Internet and World Wide Web
Chapter 2—Introduction to C++ Programming
Chapter 3—Introduction to Classes and Objects
Chapter 4—Control Statements: Part 1
Chapter 5—Control Statements: Part 2
Chapter 6—Functions and an Introduction to Recursion
Chapter 7—Arrays and Vectors
Chapter 8—Pointers and Pointer-Based Strings
Chapter 9—Classes: A Deeper Look, Part 1
Chapter 10—Classes: A Deeper Look, Part 2
Chapter 11—Operator Overloading: String and Array Objects
Chapter 12—Object-Oriented Programming: Inheritance
Chapter 13—Object-Oriented Programming: Polymorphism
Appendices in Both Small C++ How to Program, 5/e and C++ How to Program, 5/e
Operator Precedence and Associativity Chart
ASCII Character Set
C++ Internet and Web Resources
Using the Visual C++ .NET Debugger
Using the GNU C++ Debugger
Chapters in Only C++ How to Program, 5/e
Chapter 15—Stream Input/Output
Chapter 16—Exception Handling
Chapter 17—File Processing
Chapter 18—Class string and String Stream Processing
Chapter 19—Web Programming
Chapter 20—Searching and Sorting
Chapter 21—Data Structures
Chapter 22—Bits, Characters, Streams and Structures
Chapter 23—Standard Template Library
Chapter 24—Other Topics
Appendices in Only C++ How to Program, 5/e
C Legacy-Code Topics
ATM Case Study Code
UML 2 Diagrams
Introduction to XHTML
XHTML Special Characters
SafariX Textbooks Online is a new service for college students looking to save money on required or recommended textbooks for academic courses. This secure WebBooks platform creates a new option in the higher education market; an additional choice for students alongside conventional textbooks and online learning services. Pearson provides students with a WebBook at 50% of the cost of its conventional print equivalent.
SafariX WebBooks are viewed through a Web browser connected to the Internet. No special plug-ins are required and no applications need to be downloaded. Students simply log in, purchase access and begin studying. With SafariX Textbooks Online students can search the text, make notes online, print out reading assignments that incorporate their professors’ lecture notes and bookmark important passages they want to review later. They can navigate easily to a page number, reading assignment, or chapter. The Table of Contents of each WebBook appears in the left-hand column alongside the text.
We are pleased to offer students the C++ How to Program, 5/e SafariX WebBook available for fall 2005 classes. Visit www.pearsonchoices.com for more information. Other Deitel titles available as SafariX WebBooks include Java How to Program, 6/e, Small Java How to Program, 6/e, Small C++ How to Program, 5/e and Simply C++: An Application-Driven Tutorial Approach. Visit www.safarix.com/tour.html for more information.
The Deitel Buzz Online Free E-mail Newsletter
Our free e-mail newsletter, the Deitel Buzz Online is sent to approximately 38,000 opt-in, registered subscribers and includes commentary on industry trends and developments, links to free articles and resources from our published books and upcoming publications, product-release schedules, errata, challenges, anecdotes, information on our corporate instructor-led training courses and more. It’s also our way to notify our readers rapidly about issues related to C++ How to Program, 5/e. To subscribe, visit
One of the great pleasures of writing a textbook is acknowledging the efforts of many people whose names may not appear on the cover, but whose hard work, cooperation, friendship and understanding were crucial to the production of the book. Many people at Deitel & Associates, Inc. devoted long hours to working with us on this project.
• Andrew B. Goldberg is a graduate of Amherst College, where he earned a bachelor’s degree in Computer Science. Andrew updated Chapters 1–13 based on the book’s new early-classes presentation and other content revisions. He co-designed and co-authored the new, optional OOD/UML ATM case study that ap• pears in Chapters 1–7, 9 and 13. He also contributed to Chapter 19 and co-authored Appendices G and H.
• Jeff Listfield is a Computer Science graduate of Harvard College. Jeff contributed to Chapters 18, 20 and 22, Appendices A–F and co-authored Appendices L and M.
• Su Zhang holds B.Sc. and a M.Sc. degrees in Computer Science from McGill University. Su contributed to Chapters 14–24.
• Cheryl Yaeger graduated from Boston University in three years with a bachelor’s degree in Computer Science. Cheryl contributed to Chapters 4, 6, 8, 9 and 13.
• Barbara Deitel, Chief Financial Officer at Deitel & Associates, Inc. researched the quotes at the beginning of each chapter and applied copyedits to the book.
• Abbey Deitel, President of Deitel & Associates, Inc., is an Industrial Management graduate of Carnegie Mellon University. She contributed to the Preface and Chapter 1. She applied copyedits to several chapters in the book, managed the review process and suggested the theme and bug names for the cover of the book.
• Christi Kelsey is a graduate of Purdue University with a bachelor’s degree in Management and a minor in Information Systems. Christi contributed to the Preface and Chapter 1. She edited the Index, paged the manuscript and coordinated many aspects of our publishing relationship with Prentice Hall.
We are fortunate to have worked on this project with the talented and dedicated team of publishing professionals at Prentice Hall. We especially appreciate the extraordinary efforts of our Computer Science Editor, Kate Hargett and her boss and our mentor in publishing—Marcia Horton, Editorial Director of Prentice Hall’s Engineering and Computer Science Division. Jennifer Cappello did an extraordinary job recruiting the review team and managing the review process from the Prentice Hall side. Vince O’Brien, Tom Manshreck and John Lovell did a marvelous job managing the production of the book. The talents of Paul Belfanti, Carole Anson, Xiaohong Zhu and Geoffrey Cassar are evident in the re-design of the book’s interior and the new cover art, and Sarah Parker managed the publication of the book’s extensive ancillary package.
We sincerely appreciate the efforts of our fourth-edition post-publication reviewers and our fifth-edition reviewers:
Richard Albright, Goldey Beacom College
Karen Arlien, Bismarck State College
David Branigan, DeVry University, Illinois
Jimmy Chen, Salt Lake Community College
Martin Dulberg , North Carolina State University
Ric Heishman, Northern Virginia Community College
Richard Holladay, San Diego Mesa College
William Honig, Loyola University
Earl LaBatt, OPNET Technologies, Inc./ University of New Hampshire
Brian Larson, Modesto Junior College
Robert Myers, Florida State University
Gavin Osborne, Saskatchewan Institute of Applied Science and Technology
Wolfgang Pelz, The University of Akron
Donna Reese, Mississippi State University
Curtis Green, Boeing Integrated Defense Systems
Mahesh Hariharan, Microsoft
James Huddleston, Independent Consultant
Ed James-Beckham, Borland Software Corporation
Don Kostuch, Independent Consultant
Meng Lee, Hewlett-Packard
Kriang Lerdsuwanakij, Siemens Limited
William Mike Miller, Edison Design Group, Inc.
Mark Schimmel, Borland International
Vicki Scott, Metrowerks
James Snell, Boeing Integrated Defense Systems
Raymond Stephenson, Microsoft
OOD/UML Optional Software Engineering Case Study Reviewers
Sinan Si Alhir, Independent Consultant
Karen Arlien, Bismarck State College
David Branigan, DeVry University, Illinois
Martin Dulberg , North Carolina State University
Ric Heishman, Northern Virginia Community College
Richard Holladay, San Diego Mesa College
Earl LaBatt, OPNET Technologies, Inc./ University of New Hampshire
Brian Larson, Modesto Junior College
Gavin Osborne, Saskatchewan Institute of Applied Science and Technology
Praveen Sadhu, Infodat International, Inc.
Cameron Skinner, Embarcadero Technologies, Inc. / OMG
Steve Tockey, Construx Software
C++ 4/e Post-Publication Reviewers
Butch Anton, Wi-Tech Consulting
Karen Arlien, Bismarck State College
Jimmy Chen, Salt Lake Community College
Martin Dulberg, North Carolina State University
William Honig, Loyola University
Don Kostuch, Independent Consultant
Earl LaBatt, OPNET Technologies, Inc./ University of New Hampshire
Brian Larson, Modesto Junior College
Kriang Lerdsuwanakij, Siemens Limited
Robert Myers, Florida State University
Gavin Osborne, Saskatchewan Institute of Applied Science and Technology
Wolfgang Pelz, The University of Akron
David Papurt, Independent Consultant
Donna Reese, Mississippi State University
Catherine Wyman, DeVry University, Phoenix
Salih Yurttas, Texas A&M University
Under tight deadline pressure, they scrutinized every aspect of the text and made countless suggestions for improving the accuracy and completeness of the presentation.
Well, there you have it! Welcome to the exciting world of C++ and object-oriented programming. We hope you enjoy this look at contemporary computer programming. Good luck! As you read the book, we would sincerely appreciate your comments, criticisms, corrections and suggestions for improving the text. Please address all correspondence to:
We will respond promptly, and we will post corrections and clarifications on:
We hope you enjoy learning with C++ How to Program, Fifth Edition as much as we enjoyed writing it!
Dr. Harvey M. Deitel
Paul J. Deitel
About the Authors
Dr. Harvey M. Deitel, Chairman and Chief Strategy Officer of Deitel & Associates, Inc., has 43 years experience in the computing field, including extensive industry and academic experience. Dr. Deitel earned B.S. and M.S. degrees from the Massachusetts Institute of Technology and a Ph.D. from Boston University. He worked on the pioneering virtual-memory operating-systems projects at IBM and MIT that developed techniques now widely implemented in systems such as UNIX, Linux and Windows XP. He has 20 years of college teaching experience, including earning tenure and serving as the Chairman of the Computer Science Department at Boston College before founding Deitel & Associates, Inc., with his son, Paul J. Deitel. Dr. Deitel has delivered hundreds of professional seminars to major corporations, academic institutions, government organizations and the military. He and Paul are the co-authors of several dozen books and multimedia packages and they are writing many more. With translations published in Japanese, German, Russian, Spanish, Traditional Chinese, Simplified Chinese, Korean, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish, the Deitels’ texts have earned international recognition.
Paul J. Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate of MIT’s Sloan School of Management, where he studied Information Technology. Through Deitel & Associates, Inc., he has delivered C++, Java, C, Internet and World Wide Web courses to industry clients including IBM, Sun Microsystems, Dell, Lucent Technologies, Fidelity, NASA at the Kennedy Space Center, the National Severe Storm Laboratory, PalmSource, White Sands Missile Range, Rogue Wave Software, Boeing, Stratus, Cambridge Technology Partners, TJX, One Wave, Hyperion Software, Adra Systems, Entergy, CableData Systems and many other organizations. Paul is one of the world’s most experienced Java and C++ corporate trainers having taught over 100 professional Java and C++ training courses. He has also lectured on C++ and Java for the Boston Chapter of the Association for Computing Machinery. He and his father, Dr. Harvey M. Deitel, are the world’s best-selling Computer Science textbook authors.
About Deitel & Associates, Inc.
Deitel & Associates, Inc., is an internationally recognized corporate training and content-creation organization specializing in computer programming languages, Internet/World Wide Web software technology and object technology education. The company provides instructor-led courses on major programming languages and platforms such as Java, Advanced Java, C, C++, .NET programming languages, XML, Perl, Python; object technology; and Internet and World Wide Web programming. The founders of Deitel & Associates, Inc., are Dr. Harvey M. Deitel and Paul J. Deitel. The company’s clients include many of the world’s largest computer companies, government agencies, branches of the military and business organizations. Through its 29-year publishing partnership with Prentice Hall, Deitel & Associates, Inc. publishes leading-edge programming textbooks, professional books, interactive multimedia Cyber Classrooms, Complete Training Courses, Web-based training courses and course management systems e-content for popular CMSs such as WebCT, Blackboard and Pearson’s CourseCompass. Deitel & Associates, Inc., and the authors can be reached via e-mail at:
To learn more about Deitel & Associates, Inc., its publications and its worldwide Dive Into Series Corporate Training curriculum, see the last few pages of this book or visit:
and subscribe to the free Deitel Buzz Online e-mail newsletter at:
Individuals wishing to purchase Deitel books, Cyber Classrooms, Complete Training Courses and Web-based training courses can do so through:
Bulk orders by corporations and academic institutions should be placed directly with Prentice Hall. See the last few pages of this book for worldwide ordering details.