Gift Guide


See more details below
C++ for Programmers

Available on NOOK devices and apps  
  • NOOK Devices
  • Samsung Galaxy Tab 4 NOOK 7.0
  • Samsung Galaxy Tab 4 NOOK 10.1
  • NOOK HD Tablet
  • NOOK HD+ Tablet
  • NOOK eReaders
  • NOOK Color
  • NOOK Tablet
  • Tablet/Phone
  • NOOK for Windows 8 Tablet
  • NOOK for iOS
  • NOOK for Android
  • NOOK Kids for iPad
  • PC/Mac
  • NOOK for Windows 8
  • NOOK for PC
  • NOOK for Mac

Want a NOOK? Explore Now

NOOK Book (eBook)
$27.49 price
(Save 42%)$47.99 List Price


  • Classes, Objects, Encapsulation, Inheritance, Polymorphism
  • Integrated OOP Case Studies: Time, GradeBook, Employee
  • Industrial-Strength, 95-Page OOD/UML® 2 ATM Case Study
  • Standard Template Library (STL): Containers, Iterators and Algorithms
  • I/O, Types, Control Statements, Functions
  • Arrays, Vectors, Pointers, References
  • String Class, C-Style Strings
  • Operator Overloading, Templates
  • Exception Handling, Files
  • Bit and Character Manipulation
  • Boost Libraries and the Future of C++
  • GNU™ and Visual C++® Debuggers
  • And more…
  • For information on Deitel® Dive-Into® Series corporate training courses offered at customer sites worldwide (or write to
  • Download code examples
  • Check out the growing list of programming, Web 2.0 and software-related Resource Centers
  • To receive updates for this book, subscribe to the free DEITEL® BUZZ ONLINE e-mail newsletter at
  • Read archived issues of the DEITEL® BUZZ ONLINE
The professional programmer’s DEITEL® guide to C++ and object-oriented application development

Written for programmers with a background in high-level language programming, this book applies the Deitel signature live-code approach to teaching programming and explores the C++ language and C++ Standard Libraries in depth. The book presents the concepts in the context of fully tested programs, complete with syntax shading, code highlighting, code walkthroughs and program outputs. The book features 240 C++ applications with over 15,000 lines of proven C++ code, and hundreds of tips that will help you build robust applications.

Start with an introduction to C++ using an early classes and objects approach, then rapidly move on to more advanced topics, including templates, exception handling, the Standard Template Library (STL) and selected features from the Boost libraries. You’ll enjoy the Deitels’ classic treatment of object-oriented programming and the OOD/UML® 2 ATM case study, including a complete C++ implementation. When you’re finished, you’ll have everything you need to build object-oriented C++ applications.

The DEITEL® Developer Series is designed for practicing programmers. The series presents focused treatments of emerging technologies, including C++, .NET, Java™, web services, Internet and web development and more.

“An excellent ‘objects first’ coverage of C++. The example-driven presentation is enriched by the optional UML case study that contextualizes the material in an ongoing software engineering project.” –Gavin Osborne, Saskatchewan Institute of Applied Science and Technology

“Introducing the UML early on is a great idea.” –Raymond Stephenson, Microsoft

“Good use of diagrams, especially of the activation call stack and recursive functions.” –Amar Raheja, California State Polytechnic University, Pomona

“Terrific discussion of pointers–probably the best I have seen.” –Anne B. Horton, Lockheed Martin

“Great coverage of polymorphism and how the compiler implements polymorphism ‘under the hood.’” –Ed James-Beckham, Borland

“The Boost/C++0x chapter will get you up and running quickly with the memory management and regular expression libraries, plus whet your appetite for new C++ features being standardized.” –Ed Brey, Kohler Co.

“Excellent introduction to the Standard Template Library (STL). The best book on C++ programming!” –Richard Albright, Goldey-Beacom College

“Just when you think you are focused on learning one topic, suddenly you discover you’ve learned more than you expected.” –Chad Willwerth, University of Washington, Tacoma

“The most thorough C++ treatment I’ve seen. Replete with real-world case studies covering the full software development lifecycle. Code examples are extraordinary!” –Terrell Hull, Logicalis Integration Solutions/
Read More Show Less

Product Details

  • ISBN-13: 9780137018475
  • Publisher: Pearson Education
  • Publication date: 2/6/2009
  • Series: Deitel Developer Series
  • Sold by: Barnes & Noble
  • Format: eBook
  • Edition number: 1
  • Pages: 1056
  • Sales rank: 877,715
  • File size: 8 MB

Meet the Author

Paul J. Deitel and Dr. Harvey M. Deitel are the founders of Deitel & Associates, Inc., the internationally recognized programming languages authoring, corporate-training and Internet business development organization. The Deitels have written many international best-selling programming-language professional books and textbooks that millions of people worldwide have used to master C++, C, Java™, C#, Visual Basic®, Visual C++® XML, Perl, Python, and Internet and web programming.
Read More Show Less

Read an Excerpt


“The chief merit of language is clearness ...”

Welcome to C++ for Programmers! At Deitel & Associates, we write programming language professional books and textbooks for publication by Prentice Hall, deliver programming languages corporate training courses at organizations worldwide and develop Internet businesses. This book is intended for programmers who do not yet know C++, and may or may not know object-oriented programming. Features of C++ for Programmers

The Tour of the Book section of this Preface will give you a sense of C++ for Programmers’ coverage of C++ and object-oriented programming. Here’s some key features of the book:

  • Early Classes and Objects Approach. We present object-oriented programming, where appropriate, from the start and throughout the text.
  • Integrated Case Studies. We develop 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 E.
  • Unified Modeling Language™ 2 (UML 2). The Unified Modeling Language (UML) has become the preferred graphical modeling language for designers of object-oriented systems. 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 emphasize the UML in the optional OOD/UML ATM case study
  • Optional OOD/UML ATM Case Study. We introduce a concise subset of the UML 2,then guide you through a first design experience intended for the novice object-oriented designer/programmer. The case study was reviewed by a distinguished team of OOD/UML industry professionals and academics. The case study is not an exercise; rather, it’s 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.
  • 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 automatic variables of functions are maintained in memory and how a function knows where to return after it completes execution.
  • Class string. We use class string instead of C-like pointer-based char * strings for most string manipulations throughout the book. We include discussions of char * strings in Chapters 8, 10, 11 and 19 to give you practice with pointer manipulations, to illustrate dynamic memory allocation with new and delete, to build our own String class, and to prepare you for working 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 you for working with C and C++ legacy code and to use as a basis for building our own customized Array class in Chapter 11.
  • Treatment of Inheritance and Polymorphism. Chapters 12–13 include an Employee class hierarchy that makes the treatment of inheritance and polymorphism clear and accessible for programmers who are new to OOP.
  • 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 you a solid understanding of how these capabilities really work. More importantly, it helps you appreciate the overhead of polymorphism—in terms of additional memory consumption and processor time. This helps you determine when to use polymorphism and when to avoid it.
  • Standard Template Library (STL). This might be one of the most important topics in the book in terms 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 20 introduces the STL and discusses its three key components—containers, iterators and algorithms. Using STL components provides tremendous expressive power, often reducing many lines of non-STL code to a single statement.
  • ISO/IEC C++ Standard Compliance. We have audited our presentation against the most recent ISO/IEC C++ standard document for completeness and accuracy. Note: A PDF copy of the C++ standard (document number INCITS/ISO/ IEC 14882-2003) can be purchased at default.asp.
  • Future of C++. In Chapter 21, which considers the future of C++, we introduce the Boost C++ Libraries, Technical Report 1 (TR1) and C++0x. The free Boost open source libraries are created by members of the C++ community. Technical Report 1 describes the proposed changes to the C++ Standard Library, many of which are based on current Boost libraries. The C++ Standards Committee is revising the C++ Standard. The main goals for the new standard are to make C++ easier to learn, improve library building capabilities, and increase compatibility with the C programming language. The last standard was published in 1998. Work on the new standard, currently referred to as C++0x, began in 2003. The new standard is likely to be released in 2009. It will include changes to the core language and, most likely, many of the libraries in TR1. We overview the TR1 libraries and provide code examples for the “regular expression” and “smart pointer” libraries.
  • Debugger Appendices. We include two Using the Debugger appendices— Appendix G, Using the Visual Studio Debugger, and Appendix H, Using the GNU C++ Debugger.
  • Code Testing on Multiple Platforms. We tested the code examples on various popular C++ platforms. For the most part, the book’s examples port easily to standard-compliant compilers.
  • 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.

All of this was carefully reviewed by distinguished industry developers and academics. We believe that this book will provide you with an informative, interesting, challenging and entertaining C++ educational experience.

As you read this book, if you have questions, send an e-mail to; we’ll respond promptly. For updates on this book and the status of all supporting C++ software, and for the latest news on all Deitel publications and services, visit Sign up at for the free Deitel¨ Buzz Online e-mail newsletter and check out our growing list of C++ and related Resource Centers at Each week we announce our latest Resource Centers in the newsletter. Learning Features

C++ for Programmers contains a rich collection of examples. The book concentrates on the principles of good software engineering and stresses program clarity. We teach by example. We are educators who teach programming languages in industry classrooms worldwide. The Deitels have taught courses at all levels to government, industry, military and academic clients of Deitel & Associates.

Live-Code Approach. C++ for Programmers is loaded with “live-code” examples—by this we mean that each new concept is presented in the context of a complete working C++ application that is immediately followed by one or more actual executions showing the program’s inputs and outputs.

Syntax Shading. We syntax-shade all the C++ code, similar to the way most C++ integrated development environments (IDEs) and code editors syntax-color code. This greatly improves code readability—an especially important goal, given that this book contains over 15,500 lines of code. Our syntax-shading conventions are as follows:

comments appear in italic keywords appear in bold italic errors and ASP.NET script delimiters appear in bold black constants and literal values appear in bold gray all other code appears in plain black

Code Highlighting. We place white rectangles around the key code segments in each program.

Using Fonts for Emphasis. We place the key terms and the index’s page reference for each defining occurrence in bold italic 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).

Web Access. All of the source-code examples for C++ for Programmers are available for download from

Objectives. Each chapter begins with a statement of objectives. This lets you know what to expect and gives you an opportunity, after reading the chapter, to determine if you’ve met the objectives.

Quotations. The learning objectives are followed by quotations. Some are humorous; some are philosophical; others offer interesting insights. We hope that you enjoy relating the quotations to the chapter material.

Outline. The chapter outlines help you approach the material in a top-down fashion, so you can anticipate what is to come and set a comfortable and effective learning pace.

Illustrations/Figures. Abundant charts, tables, line drawings, programs and program output are included. We model the flow of control in control statements with UML activity diagrams. UML class diagrams model the fields, constructors and methods of classes. We make extensive use of six major UML diagram types in the optional OOD/UML 2 ATM case study.

Programming Tips. We include programming tips to help you focus on important aspects of program development. These tips and practices represent the best we’ve gleaned from a combined seven decades of programming experience—they provide a basis on which to build good software.


Good Programming Practice - Good Programming Practices call attention to techniques that will help you produce programs that are clearer, more understandable and more maintainable.


Common Programming Error - Pointing out these Common Programming Errors reduces the likelihood that you’ll make the same mistakes.


Error-Prevention Tip - These tips contain suggestions for exposing bugs and removing them from your programs; many describe aspects of C++ that prevent bugs from getting into programs in the first place.


Performance Tip - These tips highlight opportunities for making your programs run faster or minimizing the amount of memory that they occupy.


Portability Tip - We include Portability Tips to help you write code that will run on a variety of platforms and to explain how C++ achieves its high degree of portability.


Software Engineering Observation - The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems.

Wrap-Up Section. Each of the chapters ends with a brief “wrap-up” section that recaps the chapter content and transitions to the next chapter.

Thousands of Index Entries. We’ve included an extensive index which is especially useful when you use the book as a reference.

“Double Indexing” of C++ Live-Code Examples. For every source-code program in the book, we index the figure caption both alphabetically and as a subindex item under “Examples.” This makes it easier to find examples using particular features. Tour of the Book

You’ll now take a tour of the C++ capabilities you’ll study in C++ for Programmers. Figure 1 illustrates the dependencies among the chapters. We recommend studying the topics in the order indicated by the arrows, though other orders are possible.

Chapter 1, Introduction, discusses the origin of the C++ programming language, and introduces a typical C++ programming environment. We walk through a “test drive” of a typical C++ application on the Windows and Linux platforms. We also introduce 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 C++. The programs in this chapter illustrate how to display data on the screen, obtain data from the keyboard, make decisions and perform arithmetic operations.

Chapter 3, Introduction to Classes and Objects, provides a friendly early introduction to classes and objects. 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++. 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 an instructor 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. 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. We explain 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.

Fig. 1 C++ for Programmers chapter dependency chart.

Chapter 4, Control Statements: Part 1, focuses on the program-development process involved in creating useful classes. The chapter introduces some 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. 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. The chapter also a discusses 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 you can build your own functions. The chapter’s first example continues the GradeBook class case study with an example of a function with multiple parameters. You may 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 you’ll use throughout the book. We discuss the function call stack and activation records to explain how C++ keeps 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.

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’ll see in Chapter 8, can be treated as pointers to the array contents in memory. We then present arrays as full-fledged objects, introducing 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. The second version uses a two-dimensional array to store the grades of a number of students on multiple exams in a semester. Another key feature of this chapter is the discussion of elementary sorting and searching techniques.

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 discuss 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). We frequently use string objects (introduced in Chapter 3) in place of C-style, char * pointer-based strings. However, we include char * strings in Chapter 8 to help you master pointers and prepare for the professional world in which you’ll see a great deal of C legacy code that has been implemented over the last three decades. In C and “raw C++” arrays and strings are pointers to array and string contents in memory (even function names are pointers).

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. We discuss 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.

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

Chapter 11, Operator Overloading; String and Array Objects, presents one of the most popular topics in our C++ courses. Professionals really enjoy this material. They find it a perfect complement to the detailed discussion of crafting valuable classes in Chapters 9 and 10. Operator overloading enables you to tell the compiler how to use existing operators with objects of new types. C++ already knows how to use these operators with 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, you’ll see 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 a collection of substantial case studies including an Array class, a String class and a Date class. Using operator overloading wisely helps you add extra “polish” to your classes.

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 chapter presents a five-example sequence demonstrating private data, protected data and good software engineering with inheritance. 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. 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. 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 include 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.

Chapter 14, Templates, discusses one of C++’s more powerful software reuse features, namely templates. Function templates and class templates enable you 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. 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. We greatly enhance the treatment of templates in our discussion of the Standard Template Library (STL) containers, iterators and algorithms in Chapter 20.

Chapter 15, 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. 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 (>>). 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 you 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. We discuss rethrowing an exception, and 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.

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 your 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, Bits, Characters, C Strings and structs, 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. C++’s powerful bit-manipulation capabilities enable you 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. We discuss C-style char * string manipulation in Chapter 8, where we present the most popular string-manipulation functions. In Chapter 19, 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.

Chapter 20, Standard Template Library (STL), discusses the STL’s 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. This chapter discusses the STL’s three key components—containers (templatized data structures), iterators and algorithms. Containers are data structures capable of storing objects of any type. We’ll see that there are three container categories—first-class containers, adapters and near containers. Iterators, which have similar properties to those of pointers, are used by programs to manipulate the container elements. In fact, standard arrays can be manipulated as STL containers, using pointers as iterators. 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). Most of these use iterators to access container elements.

Chapter 21, Boost Libraries, Technical Report 1 and C++0x, focuses on the future of C++. We introduce the Boost Libraries, a collection of free, open source C++ libraries. The Boost libraries are carefully designed to work well with the C++ Standard Library. We then discuss Technical Report 1 (TR1), a description of proposed changes and additions to the Standard Library. Many of the libraries in TR1 were derived from libraries currently in Boost. The chapter briefly describes the TR1 libraries. We provide in-depth code examples for two of the most useful libraries, Boost.Regex and Boost.Smart_ptr. The Boost.Regex library provides support for regular expressions. We demonstrate how to use the library to search a string for matches to a regular expression, validate data, replace parts of a string and split a string into tokens. The Boost.Smart_ptr library provides smart pointers to help manage dynamically allocated memory. We discuss the two types of smart pointers included in TR1—shared_ptr and weak_ptr. We provide examples to demonstrate how these can be used to avoid common memory management errors. This chapter also discusses the upcoming release of the new standard for C++.

Chapter 22, Other Topics, is a collection of miscellaneous C++ topics. We discuss one more cast operator—const_cast. This operator, 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. Namespaces prevent naming collisions, which can hinder such large software efforts. 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 C++’s fundamental types.

Appendix D, Preprocessor, discusses the preprocessor’s directives. The appendix 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 appendix explains conditional compilation, which enables you 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 E, ATM Case Study Code, contains the implementation of our case study on object-oriented design with the UML. This appendix is discussed in the tour of the case study (presented shortly).

Appendix F, UML 2: Additional Diagram Types, overviews the UML 2 diagram types that are not found in the OOD/UML Case Study.

Appendix G, Using the Visual Studio Debugger, demonstrates key features of the Visual Studio 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 you learn how to use the debugger in a hands-on manner.

Appendix H, Using the GNU C++ Debugger, demonstrates key features of the GNU C++ Debugger. The appendix presents step-by-step instructions, so you learn how to use the debugger in a hands-on manner.

Bibliography. The Bibliography lists many books and articles for further reading on C++ and object-oriented programming.

Index. The comprehensive index enables you 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, you’ll be thoroughly familiar with a carefully developed and 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. 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.

Section 1.10, 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.7, (Optional) Software Engineering Case Study: Examining the ATM Requirements Specification—discusses a requirements specification that specifies the requirements for a system that we’ll 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 discuss the interaction between the ATM system specified by the requirements specification 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 Specification—begins to design the ATM system. We identify its classes, or “building blocks,” by extracting the nouns and noun phrases from the requirements specification. 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.11, (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’ll 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 specification, then place the attributes in the class diagram we created in Section 3.11.

Section 5.10, (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 specification 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 specification. However, as future chapters introduce such topics as inheritance, we’ll 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.11, (Optional) Software Engineering Case Study: Starting to Program the Classes of the ATM System—takes a break from designing the system’s behavior. 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.11 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 E.

Appendix E, 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, you’ll have completed the design and implementation of a real-world system, and should feel confident tackling larger systems.

Appendix F, UML 2: Additional Diagram Types—Overviews the UML 2 diagram types that are not found in the OOD/UML Case Study. Compilers and Other Resources

Many C++ development tools are available. We wrote C++ for Programmers primarily using Microsoft’s free Visual C++ Express Edition ( and the free GNU C++ at, which is already installed on most Linux systems and can be installed on Mac OS X systems as well. Apple includes GNU C++ in their Xcode development tools, which Max OS X users can download from tools/xcode.

Additional resources and software downloads are available in our C++ Resource Center:

and at the website for this book:

For a list of other C++ compilers that are available free for download, visit: 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.

Some older C++ compilers 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. 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. The Deitel Online Resource Centers

Our website provides Resource Centers ( on various topics including programming languages, software, Web 2.0, Internet business and open source projects. The Resource Centers evolve out of the research we do for our books and business endeavors. We’ve found many (mostly free) exceptional resources including tutorials, documentation, software downloads, articles, blogs, videos, code samples, books, e-books and more. We help you wade through the vast amount of content on the Internet by providing links to the most valuable resources. Each week we announce our latest Resource Centers in our newsletter, the Deitel¨ Buzz Online ( The following Resource Centers may be of interest to you as you read C++ for Programmers:

  • C++
  • Open Source
  • Visual C++ 2008
  • Programming Projects
  • C++ Boost Libraries
  • Eclipse
  • C++ Game Programming
  • Linux
  • Code Search Engines and Code Sites
  • .NET
  • Computer Game Programming
  • Windows Vista
  • Computing Jobs

Deitel® Buzz Online Free E-mail Newsletter

Each week, the Deitel® Buzz Online newsletter announces our latest Resource Centers 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 a good way for you to keep posted about issues related to C++ for Programmers. To subscribe, visit Deitel® LiveLessons Self-Paced Video Training

The Deitel® LiveLessons products are self-paced video training. Each collection provides approximately 14+ hours of an instructor guiding you through programming training.

Your instructor, Paul Deitel, has personally taught programming at organizations ranging from IBM to Sun Microsystems to NASA. With the powerful videos included in our LiveLessons products, you’ll learn at your own pace as Paul guides you through programming fundamentals, object-oriented programming and additional topics.

Deitel® LiveLessons products are based on its corresponding best-selling books and Paul’s extensive experience presenting hundreds corporate training seminars. To view sample videos, visit

The Java Fundamentals I and II LiveLessons are available now. For announcements about upcoming Deitel LiveLessons products, including C++ Fundamentals, C# 2008 Fundamentals and JavaScript Fundamentals, subscribe to the Deitel¨ Buzz Online email newsletter at Deitel® Dive-Into® Series Instructor-Led Training

With our corporate, on-site, instructor-led Dive-Into® Series programming training courses (Fig. 2), professionals can learn C++, Java, C, Visual Basic, Visual C#, Visual C++, Python, and Internet and web programming from the internationally recognized professionals at Deitel & Associates, Inc. Our authors, teaching staff and contract instructors have taught over 1,000,000 people in more than 100 countries how to program in almost every major programming language through:

  • Deitel Developer Series professional books
  • How to Program Series textbooks
  • University teaching
  • Professional seminars
  • Interactive multimedia CD-ROM Cyber Classrooms, Complete Training Courses and LiveLessons Video Training
  • Satellite broadcasts

We’re uniquely qualified to turn non-programmers into programmers and to help professional programmers move to new programming languages. For more information about our on-site, instructor-led Dive-Into® Series programming training, visit

Deitel Dive Into® Series Programming Training Courses


Intro to Java for Non-Programmers: Part 1
Intro to Java for Non-Programmers: Part 2
Java for Visual Basic, C or COBOL Programmers
Java for C++ or C# Programmers


Intro to C++ for Non-Programmers: Part 1
Intro to C++ for Non-Programmers: Part 2
C++ and Object Oriented Programming


Intro to C for Non-Programmers: Part 1
Intro to C for Non-Programmers: Part 2
C for Programmers
Advanced Java

Visual C# 2008

Intro to Visual C# 2008 for Non-Programmers: Part 1
Intro to Visual C# 2008 for Non-Programmers: Part 2
Visual C# 2008 for Visual Basic, C or COBOL Programmers
Visual C# 2008 for Java or C++ Programmers
Advanced Visual C# 2008

Visual Basic 2008

Intro to Visual Basic 2008 for Non-Programmers: Part 1
Intro to Visual Basic 2008 for Non-Programmers: Part 2
Visual Basic 2008 for VB6, C or COBOL Programmers
Visual Basic 2008 for Java, C# or C++ Programmers
Advanced Visual Basic 2008

Visual C++ 2008

Intro to Visual C++ 2008 for Non-Programmers: Part 1
Intro to Visual C++ 2008 for Non-Programmers: Part 2
Visual C++ 2008 and Object Oriented Programming

Internet and Web Programming

Client-Side Internet and Web Programming
Rich Internet Application (RIA) Development
Server-Side Internet and Web Programming

Fig. 2
Deitel Dive Into® Series programming training courses.Acknowledgments

It is a great pleasure to acknowledge 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 this project—thanks especially to Abbey Deitel and Barbara Deitel.

We’d also like to thank one of the participants in our Honors Internship program who contributed to this publication—Greg Ayer, a computer science major at Northeastern University.

We are fortunate to have worked on this project with the talented and dedicated team of publishing professionals at Prentice Hall. We appreciate the extraordinary efforts of Marcia Horton, Editorial Director of Prentice Hall’s Engineering and Computer Science Division, Mark Taub, Editor-in-Chief of Prentice Hall Professional, and John Fuller, Managing Editor of Prentice Hall Professional. Carole Snyder, Lisa Bailey and Dolores Mars did a remarkable job recruiting the book’s large review team and managing the review process. Sandra Schroeder designed the book’s cover. Scott Disanno and Robert Engelhardt managed the book’s production.

This book was adapted from our book C++ How to Program, 6/e. We wish to acknowledge the efforts of our reviewers on that book. Adhering to a tight time schedule, they scrutinized the text and the programs, providing countless suggestions for improving the accuracy and completeness of the presentation. C++ How to Program, 6/e Reviewers

Industry and Academic Reviewers: Dr. Richard Albright (Goldey-Beacom College), William B. Higdon (University of Indianapolis), Howard Hinnant (Apple), Anne B. Horton (Lockheed Martin), Terrell Hull (Logicalis Integration Solutions), Rex Jaeschke (Independent Consultant), Maria Jump (The University of Texas at Austin), Geoffrey S. Knauth (GNU), Don Kostuch (Independent Consultant), Colin Laplace (Freelance Software Consultant), Stephan T. Lavavej (Microsoft), Amar Raheja (California State Polytechnic University, Pomona), G. Anthony Reina (University of Maryland University College, Europe), Daveed Vandevoorde (C++ Standards Committee), Jeffrey Wiener (DEKA Research & Development Corporation, New Hampshire Community Technical College), and Chad Willwerth (University of Washington, Tacoma). Boost/C++Ox Reviewers: Edward Brey (Kohler Co.), Jeff Garland (, Douglas Gregor (Indiana University), and Bjšrn Karlsson (Author of Beyond the C++ Standard Library: An Introduction to Boost, Addison-Wesley/Readsoft, Inc.).

These reviewers 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.

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’ll respond promptly, and post corrections and clarifications on:

We hope you enjoy reading C++ for Programmers as much as we enjoyed writing it!

Paul J. Deitel
Dr. Harvey M. Deitel

© Copyright Pearson Education. All rights reserved.

Read More Show Less

Table of Contents

Preface xxi
Before You Begin xli

Chapter 1: Introduction 1

1.1 Introduction 2
1.2 History of C and C++ 3
1.3 C++ Standard Library 4
1.4 Key Software Trend: Object Technology 5
1.5 Typical C++ Development Environment 6
1.6 Notes About C++ and C++ for Programmers 8
1.7 Test-Driving a C++ Application 9
1.8 Software Technologies 15
1.9 Future of C++: Open Source Boost Libraries, TR1 and C++0x 16
1.10 Software Engineering Case Study: Introduction to Object Technology and the UML 16
1.11 Wrap-Up 21
1.12 Web Resources 22

Chapter 2: Introduction to C++ Programming 24
2.1 Introduction 25
2.2 First Program in C++: Printing a Line of Text 25
2.3 Modifying Our First C++ Program 28
2.4 Another C++ Program: Adding Integers 29
2.5 Arithmetic 33
2.6 Decision Making: Equality and Relational Operators 35
2.7 (Optional) Software Engineering Case Study: Examining the ATM Requirements Specification 38
2.8 Wrap-Up 47

Chapter 3: Introduction to Classes and Objects 48
3.1 Introduction 49
3.2 Classes, Objects, Member Functions and Data Members 49
3.3 Overview of the Chapter Examples 51
3.4 Defining a Class with a Member Function 52
3.5 Defining a Member Function with a Parameter 55
3.6 Data Members, set Functions and get Functions 58
3.7 Initializing Objects with Constructors 65
3.8 Placing a Class in a Separate File for Reusability 69
3.9 Separating Interface from Implementation 73
3.10 Validating Data with set Functions 79
3.11 (Optional) Software Engineering Case Study: Identifying the Classes in the ATM Requirements Specification 84
3.12 Wrap-Up 92

Chapter 4: Control Statements: Part 1 93
4.1 Introduction 94
4.2 Control Structures 94
4.3 if Selection Statement 97
4.4 if…else Double-Selection Statement 98
4.5 while Repetition Statement 102
4.6 Counter-Controlled Repetition 104
4.7 Sentinel-Controlled Repetition 108
4.8 Nested Control Statements 115
4.9 Assignment Operators 118
4.10 Increment and Decrement Operators 119
4.11 (Optional) Software Engineering Case Study: Identifying Class Attributes in the ATM System 122
4.12 Wrap-Up 127

Chapter 5: Control Statements: Part 2 128
5.1 Introduction 129
5.2 Essentials of Counter-Controlled Repetition 129
5.3 for Repetition Statement 131
5.4 Examples Using the for Statement 134
5.5 do…while Repetition Statement 139
5.6 switch Multiple-Selection Statement 141
5.7 break and continue Statements 151
5.8 Logical Operators 153
5.9 Confusing the Equality (==) and Assignment (=) Operators 158
5.10 (Optional) Software Engineering Case Study: Identifying Objects’ States and Activities in the ATM System 159
5.11 Wrap-Up 163

Chapter 6: Functions and an Introduction to Recursion 165
6.1 Introduction 166
6.2 Program Components in C++ 167
6.3 Math Library Functions 167
6.4 Function Definitions with Multiple Parameters 168
6.5 Function Prototypes and Argument Coercion 173
6.6 C++ Standard Library Header Files 176
6.7 Case Study: Random Number Generation 178
6.8 Case Study: Game of Chance; Introducing enum 184
6.9 Storage Classes 187
6.10 Scope Rules 190
6.11 Function Call Stack and Activation Records 193
6.12 Functions with Empty Parameter Lists 197
6.13 Inline Functions 198
6.14 References and Reference Parameters 200
6.15 Default Arguments 205
6.16 Unary Scope Resolution Operator 207
6.17 Function Overloading 208
6.18 Function Templates 211
6.19 Recursion 213
6.20 Example Using Recursion: Fibonacci Series 217
6.21 Recursion vs. Iteration 220
6.22 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System 222
6.23 Wrap-Up 229

Chapter 7: Arrays and Vectors 230
7.1 Introduction 231
7.2 Arrays 232
7.3 Declaring Arrays 234
7.4 Examples Using Arrays 234
7.5 Passing Arrays to Functions 250
7.6 Case Study: Class GradeBook Using an Array to Store Grades 255
7.7 Searching Arrays with Linear Search 262
7.8 Sorting Arrays with Insertion Sort 263
7.9 Multidimensional Arrays 265
7.10 Case Study: Class GradeBook Using a Two-Dimensional Array 268
7.11 Introduction to C++ Standard Library Class Template vector 275
7.12 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System 281
7.13 Wrap-Up 288

Chapter 8: Pointers and Pointer-Based Strings 289
8.1 Introduction 290
8.2 Pointer Variable Declarations and Initialization 290
8.3 Pointer Operators 292
8.4 Passing Arguments to Functions by Reference with Pointers 295
8.5 Using const with Pointers 299
8.6 Selection Sort Using Pass-by-Reference 306
8.7 sizeof Operator 309
8.8 Pointer Expressions and Pointer Arithmetic 312
8.9 Relationship Between Pointers and Arrays 315
8.10 Arrays of Pointers 319
8.11 Case Study: Card Shuffling and Dealing Simulation 320
8.12 Function Pointers 324
8.13 Introduction to Pointer-Based String Processing 330
8.14 Wrap-Up 340

Chapter 9: Classes: A Deeper Look, Part 1 342
9.1 Introduction 343
9.2 Time Class Case Study 344
9.3 Class Scope and Accessing Class Members 350
9.4 Separating Interface from Implementation 352
9.5 Access Functions and Utility Functions 353
9.6 Time Class Case Study: Constructors with Default Arguments 356
9.7 Destructors 361
9.8 When Constructors and Destructors Are Called 362
9.9 Time Class Case Study: A Subtle Trap–Returning a Reference to a private Data Member 366
9.10 Default Memberwise Assignment 368
9.11 (Optional) Software Engineering Case Study: Starting to Program the Classes of the ATM System 371
9.12 Wrap-Up 378

Chapter 10: Classes: A Deeper Look, Part 2 380
10.1 Introduction 381
10.2 const (Constant) Objects and const Member Functions 381
10.3 Composition: Objects as Members of Classes 391
10.4 friend Functions and friend Classes 398
10.5 Using the this Pointer 402
10.6 Dynamic Memory Management with Operators new and delete 407
10.7 static Class Members 409
10.8 Data Abstraction and Information Hiding 415
10.9 Container Classes and Iterators 418
10.10 Proxy Classes 418
10.11 Wrap-Up 422

Chapter 11: Operator Overloading; String and Array Objects 423
11.1 Introduction 424
11.2 Fundamentals of Operator Overloading 425
11.3 Restrictions on Operator Overloading 426
11.4 Operator Functions as Class Members vs. Global Functions 428
11.5 Overloading Stream Insertion and Stream Extraction Operators 429
11.6 Overloading Unary Operators 433
11.7 Overloading Binary Operators 433
11.8 Case Study: Array Class 434
11.9 Converting between Types 446
11.10 Case Study: String Class 447
11.11 Overloading ++ and -- 459
11.12 Case Study: A Date Class 461
11.13 Standard Library Class string 465
11.14 explicit Constructors 469
11.15 Wrap-Up 473

Chapter 12: Object-Oriented Programming: Inheritance 474
12.1 Introduction 475
12.2 Base Classes and Derived Classes 476
12.3 protected Members 479
12.4 Relationship between Base Classes and Derived Classes 479
12.5 Constructors and Destructors in Derived Classes 511
12.6 public, protected and private Inheritance 519
12.7 Software Engineering with Inheritance 519
12.8 Wrap-Up 521

Chapter 13: Object-Oriented Programming: Polymorphism 522
13.1 Introduction 523
13.2 Polymorphism Examples 525
13.3 Relationships Among Objects in an Inheritance Hierarchy 526
13.4 Type Fields and switch Statements 544
13.5 Abstract Classes and Pure virtual Functions 544
13.6 Case Study: Payroll System Using Polymorphism 546
13.7 (Optional) Polymorphism, Virtual Functions and Dynamic Binding “Under the Hood” 564
13.8 Case Study: Payroll System Using Polymorphism and Runtime Type Information with Downcasting, dynamic_cast, typeid and type_info 568
13.9 Virtual Destructors 571
13.10 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System 572
13.11 Wrap-Up 580

Chapter 14 Templates 581
14.1 Introduction 582
14.2 Function Templates 583
14.3 Overloading Function Templates 586
14.4 Class Templates 586
14.5 Nontype Parameters and Default Types for Class Templates 593
14.6 Notes on Templates and Inheritance 594
14.7 Notes on Templates and Friends 594
14.8 Notes on Templates and static Members 595
14.9 Wrap-Up 596

Chapter 15: Stream Input/Output 597
15.1 Introduction 598
15.2 Streams 599
15.3 Stream Output 603
15.4 Stream Input 604
15.5 Unformatted I/O Using read, write and gcount 608
15.6 Introduction to Stream Manipulators 609
15.7 Stream Format States and Stream Manipulators 615
15.8 Stream Error States 625
15.9 Tying an Output Stream to an Input Stream 628
15.10 Wrap-Up 628

Chapter 16: Exception Handling 629
16.1 Introduction 630
16.2 Exception-Handling Overview 631
16.3 Example: Handling an Attempt to Divide by Zero 631
16.4 When to Use Exception Handling 637
16.5 Rethrowing an Exception 638
16.6 Exception Specifications 640
16.7 Processing Unexpected Exceptions 641
16.8 Stack Unwinding 641
16.9 Constructors, Destructors and Exception Handling 643
16.10 Exceptions and Inheritance 644
16.11 Processing new Failures 644
16.12 Class auto_ptr and Dynamic Memory Allocation 648
16.13 Standard Library Exception Hierarchy 651
16.14 Other Error-Handling Techniques 652
16.15 Wrap-Up 653

Chapter 17: File Processing 654
17.1 Introduction 655
17.2 Data Hierarchy 655
17.3 Files and Streams 657
17.4 Creating a Sequential File 658
17.5 Reading Data from a Sequential File 662
17.6 Updating Sequential Files 669
17.7 Random-Access Files 669
17.8 Creating a Random-Access File 670
17.9 Writing Data Randomly to a Random-Access File 675
17.10 Reading from a Random-Access File Sequentially 677
17.11 Case Study: A Transaction-Processing Program 680
17.12 Overview of Object Serialization 687
17.13 Wrap-Up 687

Chapter 18: Class string and String Stream Processing 688
18.1 Introduction 689
18.2 string Assignment and Concatenation 690
18.3 Comparing strings 692
18.4 Substrings 695
18.5 Swapping strings 696
18.6 string Characteristics 697
18.7 Finding Substrings and Characters in a string 699
18.8 Replacing Characters in a string 701
18.9 Inserting Characters into a string 703
18.10 Conversion to C-Style Pointer-Based char * Strings 704
18.11 Iterators 706
18.12 String Stream Processing 707
18.13 Wrap-Up 710

Chapter 19: Bits, Characters, C Strings and structs 711
19.1 Introduction 712
19.2 Structure Definitions 712
19.3 Initializing Structures 715
19.4 Using Structures with Functions 715
19.5 typedef 715
19.6 Example: High-Performance Card Shuffling and Dealing Simulation 716
19.7 Bitwise Operators 719
19.8 Bit Fields 728
19.9 Character-Handling Library 732
19.10 Pointer-Based String-Conversion Functions 738
19.11 Search Functions of the Pointer-Based String-Handling Library 743
19.12 Memory Functions of the Pointer-Based String-Handling Library 748
19.13 Wrap-Up 753

Chapter 20: Standard Template Library (STL) 754
20.1 Introduction to the Standard Template Library (STL) 756
20.2 Sequence Containers 768
20.3 Associative Containers 782
20.4 Container Adapters 791
20.5 Algorithms 796
20.6 Class bitset 827
20.7 Function Objects 831
20.8 Wrap-Up 834
20.9 STL Web Resources 835

Chapter 21: Boost Libraries, Technical Report 1 and C++0x 836
21.1 Introduction 837
21.2 Deitel Online C++ and Related Resource Centers 837
21.3 Boost Libraries 838
21.4 Adding a New Library to Boost 838
21.5 Installing the Boost Libraries 839
21.6 Boost Libraries in Technical Report 1 (TR1) 839
21.7 Regular Expressions with the Boost.Regex Library 842
21.8 Smart Pointers with Boost.Smart_ptr 851
21.9 Technical Report 1 862
21.10 C++0x 863
21.11 Core Language Changes 863
21.12 Wrap-Up 868

Chapter 22: Other Topics 869
22.1 Introduction 870
22.2 const_cast Operator 870
22.3 namespaces 872
22.4 Operator Keywords 876
22.5 mutable Class Members 878
22.6 Pointers to Class Members (.* and ->*) 880
22.7 Multiple Inheritance 882
22.8 Multiple Inheritance and virtual Base Classes 887
22.9 Wrap-Up 891

Appendix A: Operator Precedence and Associativity Chart 892
A.1 Operator Precedence 892

Appendix B: ASCII Character Set 895

Appendix C: Fundamental Types 896

Appendix D: Preprocessor 898
D.1 Introduction 899
D.2 The #include Preprocessor Directive 899
D.3 The #define Preprocessor Directive: Symbolic Constants 900
D.4 The #define Preprocessor Directive: Macros 900
D.5 Conditional Compilation 902
D.6 The #error and #pragma Preprocessor Directives 903
D.7 Operators # and ## 904
D.8 Predefined Symbolic Constants 904
D.9 Assertions 905
D.10 Wrap-Up 905

Appendix E: ATM Case Study Code 906
E.1 ATM Case Study Implementation 906
E.2 Class ATM 907
E.3 Class Screen 914
E.4 Class Keypad 915
E.5 Class CashDispenser 916
E.6 Class DepositSlot 918
E.7 Class Account 919
E.8 Class BankDatabase 921
E.9 Class Transaction 925
E.10 Class BalanceInquiry 927
E.11 Class Withdrawal 929
E.12 Class Deposit 934
E.13 Test Program ATMCaseStudy.cpp 937
E.14 Wrap-Up 937

Appendix F: UML 2: Additional Diagram Types 938
F.1 Introduction 938
F.2 Additional Diagram Types 938

Appendix G: Using the Visual Studio Debugger 940
G.1 Introduction 941
G.2 Breakpoints and the Continue Command 941
G.3 Locals and Watch Windows 946
G.4 Controlling Execution Using the Step Into, Step Over, Step Out and Continue Commands 949
G.5 Autos Window 952
G.6 Wrap-Up 953

Appendix H: Using the GNU C++ Debugger 954
H.1 Introduction 955
H.2 Breakpoints and the run, stop, continue and print Commands 955
H.3 print and set Commands 962
H.4 Controlling Execution Using the step, finish and next Commands 964
H.5 watch Command 966
H.6 Wrap-Up 968

Bibliography 970
Index 976

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star


4 Star


3 Star


2 Star


1 Star


Your Rating:

Your Name: Create a Pen Name or

Barnes & Review Rules

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

Reviews by Our Customers Under the Age of 13

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

What to exclude from your review:

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

Reviews should not contain any of the following:

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


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

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

Create a Pen Name

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

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

Continue Anonymously

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