Deitel® Developer SeriesAJAX, Rich Internet Applications and Web Development for Programmers C++ for Programmers C# 2008 for Programmers, 3/E iPhone for ProgrammersJava for ProgrammersJa
Trang 3D e i t e l ® S e r
How To Program Series
Java How to Program, 8/E
Java How to Program, Late Objects Version, 8/E
C++ How to Program, 7/E
C How to Program, 6/E
Internet & World Wide Web How to Program, 4/E
Visual Basic® 2008 How to Program
Visual C#® 2008 How to Program, 3/E
Visual C++® 2008 How to Program, 2/E
Small Java™ How to Program, 6/E
Small C++ How to Program, 5/E
Simply Visual Basic® 2008, 3/E: An Application-Driven Tutorial Approach
CourseSmart Web Books
www.deitel.com/books/CourseSmart/
C++ How to Program, 5/E & 6/E
Java How to Program, 6/E, 7/E & 8/E
i e s P a g e
Trang 4Deitel® Developer Series
AJAX, Rich Internet Applications and
Web Development for Programmers
C++ for Programmers
C# 2008 for Programmers, 3/E
iPhone for ProgrammersJava for ProgrammersJavascript for Programmers
LiveLessons Video Learning Products
www.deitel.com/books/LiveLessons/
Java Fundamentals Parts 1 and 2
C# Fundamentals Parts 1 and 2
C++ Fundamentals Parts 1 and 2JavaScript Fundamentals Parts 1 and 2
To receive updates on Deitel publications, Resource Centers, training courses, partner
offers and more, please register for the free Deitel ® Buzz Online e-mail newsletter at:
For information on government and corporate Dive-Into ® Series on-site seminars
offered by Deitel & Associates, Inc worldwide, visit:
www.deitel.com/ResourceCenters.html
Trang 5Vice President and Editorial Director, ECS: Marcia J Horton
Editor-in-Chief, Computer Science: Michael Hirsch
Associate Editor: Carole Snyder
Supervisor/Editorial Assistant: Dolores Mars
Director of Team-Based Project Management: Vince O’Brien
Senior Managing Editor: Scott Disanno
Managing Editor: Robert Engelhardt
A/V Production Editor: Greg Dulles
Art Director: Kristine Carney
Cover Design: Abbey S Deitel, Harvey M Deitel, Francesco Santalucia, Kristine Carney
Interior Design: Harvey M Deitel, Kristine Carney
Manufacturing Manager: Alexis Heydt-Long
Manufacturing Buyer: Lisa McDowell
Director of Marketing: Margaret Waples
Marketing Manager: Erin Davis
© 2010 by Pearson Education, Inc.
Upper Saddle River, New Jersey 07458
The authors and publisher of this book have used their best efforts in preparing this book These efforts include the development, research, and testing of the theories and programs to determine their effectiveness The authors and pub- lisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in this book The authors and publisher shall not be liable in any event for incidental or consequential dam- ages in connection with, or arising out of, the furnishing, performance, or use of these programs.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks and registered trademarks Where those designations appear in this book, and Prentice Hall and the authors were aware
of a trademark claim, the designations have been printed in initial caps or all caps All product names mentioned remain trademarks or registered trademarks of their respective owners.
All rights reserved No part of this book may be reproduced, in any form or by any means, without permission in writing from the publisher.
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
ISBN-10: 0-13-611726-0
ISBN-13: 978-0-13-611726-1
Pearson Education Ltd., London
Pearson Education Australia Pty Ltd., Sydney
Pearson Education Singapore, Pte Ltd.
Pearson Education North Asia Ltd., Hong Kong
Pearson Education Canada, Inc., Toronto
Pearson Educación de Mexico, S.A de C.V.
Pearson Education–Japan, Tokyo
Pearson Education Malaysia, Pte Ltd.
Pearson Education, Inc., Upper Saddle River, New Jersey
Trang 7Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc in the United States and other countries Pearson Education is independent of Sun Microsystems, Inc Microsoft, Internet Explorer and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries
Pong ® classic video game courtesy of Atari Interactive, Inc ©2009 Atari Interactive, Inc All rights reserved Used with permission.
UNIX is a registered trademark of The Open Group.
Trang 8In memory of Joseph Weizenbaum
MIT Professor Emeritus of Computer Science: For making us think.
Paul and Harvey Deitel
Trang 9Our Resource Centers focus on the vast amounts of free content available online Find resources,downloads, tutorials, documentation, books, e-books, journals, articles, blogs, RSS feeds and more
on many of today’s hottest programming and technology topics For the most up-to-date list of ourResource Centers, visit:
www.deitel.com/ResourceCenters.html
Let us know what other Resource Centers you’d like to see! Also, please register for the free Deitel ®
Buzz Online e-mail newsletter at:
Visual Studio Team System Web 3D Technologies Web Services Windows Presentation Foundation XHTML XML
Games and Game Programming
Computer Game gramming Computer Games Mobile Gaming Sudoku
Pro-Internet Business
Affiliate Programs Competitive Analysis Facebook Social Ads Google AdSense Google Analytics Google Services Internet Advertising Internet Business Initiative Internet Public Relations Link Building Location-Based Services Online Lead Generation Podcasting
Search Engine tion
Optimiza-Selling Digital Content Sitemaps
Web Analytics Website Monetization YouTube and AdSense
Java
Java Java Certification and Assessment Testing Java Design Patterns Java EE 5
Java SE 6 Java SE 7 (Dolphin) Resource Center JavaFX
Microsoft
ASP.NET ASP.NET 3.5 ASP.NET Ajax C#
DotNetNuke (DNN) Internet Explorer 7 (IE7) Microsoft LINQ NET NET 3.0 NET 3.5 SharePoint Silverlight Visual Basic Visual C++
Visual Studio Team System Windows Presentation Foundation Windows Vista Microsoft Popfly
Open Source and LAMP Stack
Apache DotNetNuke (DNN) Eclipse
Firefox Linux MySQL Open Source Perl PHP Python Ruby
Software
Apache DotNetNuke (DNN) Eclipse
Firefox Internet Explorer 7 (IE7) Linux
MySQL Open Source
Search Engines SharePoint Skype Web Servers Wikis Windows Vista
Web 2.0
Alert Services Attention Economy Blogging Building Web Communities Community Generated Content
Facebook Developer Platform Facebook Social Ads Google Base Google Video Google Web Toolkit (GWT) Internet Video Joost Location-Based Services Mashups
Microformats Recommender Systems RSS
Social Graph Social Media Social Networking Software as a Service (SaaS)
Virtual Worlds Web 2.0 Web 3.0 Widgets
Dive Into® Web 2.0 eBook
Web 2 eBook
Other Topics
Computer Games Computing Jobs Gadgets and Gizmos Ring Tones Sudoku
Trang 10Chapters 23–27 and Appendices F–I are PDF documents posted online at the book’s
Companion Website (located at www.pearsonhighered.com/deitel ).
1.7 Machine Languages, Assembly Languages
1.18 Future of C++: Open Source Boost Libraries, TR1 and C++0x 23
1.19 Software Engineering Case Study: Introduction to Object Technology
Contents
Trang 115.9 Confusing the Equality (==) and Assignment (=) Operators 191
Trang 12Contents xi
7.4.1 Declaring an Array and Using a Loop to Initialize the
7.4.2 Initializing an Array in a Declaration with an Initializer List 287
7.4.3 Specifying an Array’s Size with a Constant Variable and
7.4.5 Using Bar Charts to Display Array Data Graphically 291
7.6 Case Study: Class GradeBook Using an Array to Store Grades 303
7.10 Case Study: Class GradeBook Using a Two-Dimensional Array 316
Trang 137.11 Introduction to C++ Standard Library Class Template vector 323
9.6 Time Class Case Study: Constructors with Default Arguments 409
9.9 Time Class Case Study: A Subtle Trap—Returning a Reference to a
Trang 14Contents xiii
11.4 Operator Functions as Class Members vs Global Functions 470
11.5 Overloading Stream Insertion and Stream Extraction Operators 472
12.4.2 Creating a BasePlusCommissionEmployee Class Without
13.3 Relationships Among Objects in an Inheritance Hierarchy 575
13.3.1 Invoking Base-Class Functions from Derived-Class Objects 576
13.3.2 Aiming Derived-Class Pointers at Base-Class Objects 583
13.3.3 Derived-Class Member-Function Calls via Base-Class Pointers 584
Trang 1513.3.5 Summary of the Allowed Assignments Between Base-Class
13.6.5 Creating Indirect Concrete Derived Class
13.7 (Optional) Polymorphism, Virtual Functions and Dynamic Binding
13.8 Case Study: Payroll System Using Polymorphism and Runtime Type
Information with Downcasting, dynamic_cast, typeid and type_info 616
14.5 Nontype Parameters and Default Types for Class Templates 638
15.4.2 istream Member Functions peek, putback and ignore 655
Trang 16Contents xv
15.7.5 Floating-Point Numbers; Scientific and Fixed Notation
15.7.8 Setting and Resetting the Format State via Member
Trang 1717.9 Writing Data Randomly to a Random-Access File 733
Trang 1821.12 Search Functions of the Pointer-Based String-Handling Library 890
21.13 Memory Functions of the Pointer-Based String-Handling Library 895
22.5.3 remove, remove_if, remove_copy and remove_copy_if 962
22.5.4 replace, replace_if, replace_copy and replace_copy_if 964
Trang 1922.5.13 min and max 985
Chapters 23–27 are PDF documents posted online at the book’s Companion Website
25 ATM Case Study, Part 1: Object-Oriented
Design with the UML LXVII
Trang 20Contents xix
25.3 Identifying the Classes in the ATM Requirements Document LXXVI
26 ATM Case Study, Part 2: Implementing
an Object-Oriented Design CIX
27 Game Programming with Ogre CLVIII
Trang 21A Operator Precedence and Associativity 1006
D.2 Abbreviating Binary Numbers as Octal and Hexadecimal Numbers 1015
D.3 Converting Octal and Hexadecimal Numbers to Binary Numbers 1016
D.4 Converting from Binary, Octal or Hexadecimal to Decimal 1016
D.5 Converting from Decimal to Binary, Octal or Hexadecimal 1017
Appendices on the Web 1036
Appendices F–I are PDF documents posted online at the book’s Companion Website
(located at www.pearsonhighered.com/deitel ).
F C Legacy Code Topics CCV
F.2 Redirecting Input/Output on UNIX/Linux/Mac OS X and
Trang 22H Using the Visual Studio Debugger CCXXXI
H.3 Locals and Watch Windows CCXXXVIII
H.4 Controlling Execution Using the Step Into, Step Over, Step Out
I Using the GNU C++ Debugger CCXLVII
I.2 Breakpoints and the run, stop, continue and print Commands CCXLVIII
I.4 Controlling Execution Using the step, finish and next Commands CCLVI
Trang 24“The chief merit of language is clearness …”
—Galen
Welcome to the world of C++ programming and C++ How to Program, Seventh Edition!
This book presents leading-edge computing technologies for students, instructors andsoftware development professionals
At the heart of the book is the Deitel signature “live-code approach.” Concepts arepresented in the context of complete working C++ programs, rather than in code snippets.Each code example is immediately followed by one or more sample executions All thesource code is available at www.deitel.com/books/cpphtp7/
New and Updated Features
Here are the updates we’ve made for C++ How to Program, 7/e:
• “Making a Difference” Exercise Sets We encourage you to use computers and the
Internet to research and solve problems that really matter These new exercises aremeant to increase awareness of important issues the world is facing We hopeyou’ll approach them with your own values, politics and beliefs
• Prefer string Objects to C Strings C++ offers two types of strings—string classobjects (which we use starting in Chapter 3) and C-style, pointer-based strings
We continue to include some early discussions of C strings to give you practicewith pointer manipulations, to illustrate dynamic memory allocation with newand delete and to prepare you for working with C strings in the “legacy code”that you’ll encounter in industry In new development, you should favor stringclass objects We’ve replaced most occurrences of C strings with instances of C++class string to make programs more robust and eliminate many of the securityproblems that can be caused by manipulating C strings
• Prefer vector s to C Arrays Similarly, C++ offers two types of arrays—vectorclass objects (which we use starting in Chapter 7) and C-style, pointer-based ar-rays As appropriate, we use class template vector instead of C arrays throughoutthe book However, we begin by discussing C arrays in Chapter 7 to prepare youfor working with legacy code and to use as a basis for building your own custom-ized Array class in Chapter 11, Operator Overloading
• New Companion Website ( www.pearsonhighered.com/deitel/ ) This edition’s
Companion Website includes a wealth of material to help you with your study ofC++ programming We provide an extensive number of VideoNotes that walkyou through the code examples in 14 of the key chapters, solutions to many ofthe book’s exercises, bonus chapters, and more (see the Companion Website sec-tion later in this Preface)
Preface
Trang 25• Dynamic Memory Allocation We moved dynamic memory allocation later in the
book to Chapter 11, where it’s first needed The “proxy class” discussion (whichuses dynamic memory) has also been moved to Chapter 11
• Titled Programming Exercises We’ve titled all the programming exercises This
and the previous two features help instructors tune assignments for their classes
• Eliminated “Magic” Numbers We eliminated all uses of truly “magic” numbers
and replaced them with named constants or enums as appropriate In a few cases inwhich the context is absolutely clear, we don’t consider numbers to be “magic.”
• Enhanced Use of const We increased our use of const bookwide to encouragebetter software engineering
• Eliminated “ return 0;”. According to the C++ standard, any main function thatdoes not contain “return 0;” as its last statement is assumed to return 0 For thisreason, we’ve eliminated “return 0;” from all but the first program in the book
• Use “using namespace std;” Previously, we specified a using declaration forevery individual item that we referenced from a C++ Standard Library header file.Since these items are well known and unlikely to have name collisions with otherC++ libraries, we now use “using namespace std;” for all C++ Standard Librarycomponents from Chapter 3 forward This simplifies the programs and savesmany lines of code
• New Design The book has a new interior design that graphically serves to
orga-nize, clarify and highlight the information, and enhances the book’s pedagogy
• Reorganized Optional OOD Case Study We tuned the Object-Oriented Design/
UML automated teller machine (ATM) case study and reorganized it into twooptional chapters (25 and 26) that present the ATM’s design and complete codeimplementation This is a nice business example that most students can relate to.Working through these two chapters as a unit will help you tie together many ofthe object-oriented programming (OOP) concepts you learn in Chapters 1–13
A key concept in OOP is the interactions among objects In most textbooks, thecode examples create and use only one or two objects The ATM case study gives
you the opportunity to examine the interactions among many objects that
pro-vide the functionality of a substantial system For instructors who wish to coverthe case study in a distributed manner, we’ve indicated where each section inChapters 25 and 26 can be covered inline with earlier chapters in the book
• Function Pointer Exercises We added several real-world function-pointers
exer-cises These are available at the Companion Website and at www.deitel.com/ books/cpphtp7/
• Improved Terminology Sections We’ve added page numbers for the defining
occurrences of all terms in the terminology lists for easy reference
New Features in the Next C++ Standard
We discuss four new language features that will be part of the next C++ standard and arealready implemented by some of today’s C++ compilers These include:
• Initializer Lists for User-Defined Types These enable objects of your own types
to be initialized using the same syntax as built-in arrays
Trang 26Other Features xxv
• Range-Based for Statement A version of the for statement that iterates over allthe elements of an array or container (such as an object of the vector class)
• Lambda Expressions These enable you to create anonymous functions that can
be passed to other functions as arguments
• Concepts These enable template programmers to specify the requirements for
data types that will be used with a particular template Compilers can then vide more meaningful error messages when data types do not meet a template’srequirements
pro-Other Features
Other features of C++ How to Program, 7/e, include:
• Game Programming The computer-game industry’s revenues are already greater
than those of the first-run movie business, creating lots of career opportunities.Chapter 27, Game Programming with Ogre, introduces game programming andgraphics with the open source Ogre 3D graphics engine We discuss basic issuesinvolved in game programming Then we show how to use Ogre to create a sim-ple game featuring a play mechanic similar to the classic video game Pong®, orig-inally developed by Atari We demonstrate how to create a scene with 3D colorgraphics, smoothly animate moving objects, use timers to control animationspeed, detect collisions between objects, add sound, accept keyboard input anddisplay text output
• Future of C++ Chapter 23 considers the future of C++—we introduce the Boost
C++ Libraries, Technical Report 1 (TR1) and C++0x The free Boost open sourcelibraries are created by members of the C++ community Technical Report 1 de-scribes the proposed changes to the C++ Standard Library, many of which arebased on current Boost libraries The C++ Standards Committee is revising theC++ Standard The main goals for the new standard are to make C++ easier tolearn, improve library building capabilities, and increase compatibility with the
C programming language The last standard was published in 1998 The newstandard is likely to be released in 2010 or 2011 It will include changes to thecore language and many of the libraries in TR1 We overview the Boost librariesand provide code examples for the “regular expression” and “smart pointer” li-braries Regular expressions are used to match specific character patterns in text.They can be used, for example, to validate data to ensure that it’s in a particularformat, to replace parts of one string with another, or to split a string Many com-mon bugs in C and C++ code are related to pointers, a powerful programmingcapability you’ll study in Chapter 8, Pointers Smart pointers help you avoid er-rors by providing additional functionality to standard pointers
• Integrated Case Studies We provide several case studies spanning multiple sections
and chapters These include the development of the GradeBook class in Chapters 3–
7, the Time class in Chapters 9–10, the Employee class in Chapters 12–13, and theoptional OOD/UML ATM case study in Chapters 25–26
• Integrated GradeBook Case Study The GradeBook case study uses classes and jects in Chapters 3–7 to incrementally build a GradeBook class that represents aninstructor’s grade book and performs various calculations based on a set of stu-
Trang 27ob-dent grades, such as calculating the average grade, finding the maximum andminimum, and printing a bar chart.
• Unified Modeling Language™ 2 (UML 2) The Unified Modeling Language
(UML) has become the preferred graphical modeling language for designers ofobject-oriented systems We use UML class diagrams to visually represent classesand their inheritance relationships, and we use UML activity diagrams to dem-onstrate the flow of control in each of C++’s control statements We use six types
of UML diagrams in the optional OOD/UML ATM case study
• Compilation and Linking Process for Multiple-Source-File Programs Chapter 3
includes a detailed diagram and discussion of the compilation and linking processthat produces an executable program
• Function Call Stack Explanation In Chapter 6, we provide a detailed discussion
(with illustrations) of the function call stack and activation records to explainhow 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 functionknows where to return after it completes execution
• Tuned Treatment of Inheritance and Polymorphism Chapters 12–13 have been
carefully tuned using an Employee class hierarchy to make the treatment of itance and polymorphism clear and accessible for students who are new to OOP
inher-• Discussion and Illustration of How Polymorphism Works “Under the Hood.”
Chapter 13 contains a detailed diagram and explanation of how C++ can ment polymorphism, virtual functions and dynamic binding internally Thisgives students a solid understanding of how these capabilities really work
imple-• Standard Template Library (STL) This might be one of the most important
top-ics in the book in terms of your appreciation of software reuse The STL definespowerful, template-based, reusable components that implement many commondata structures and algorithms used to process those data structures Chapter 22introduces the STL and discusses its three key components—containers, iteratorsand algorithms We show that using STL components provides tremendous ex-pressive power, often reducing many lines of code to a single statement
• ISO/IEC C++ Standard Compliance We’ve audited our presentation against the
most recent ISO/IEC C++ standard document
• Debugger Appendices We provide two Using the Debugger appendices on the
book’s Companion Website—Appendix H, Using the Visual Studio Debugger,and Appendix I, Using the GNU C++ Debugger
• Code Testing on Multiple Platforms We tested the code examples on various
popular C++ platforms including GNU C++ on Linux and Microsoft and VisualC++ on Windows For the most part, the book’s examples port to popular stan-dard-compliant compilers
We believe that this book and its support materials will give you an informative, esting, challenging and entertaining C++ educational experience
inter-As you read the book, if you have questions, send an e-mail to deitel@deitel.com;we’ll respond promptly For updates on this book and the status of all supporting C++ soft-ware, and for the latest news on all Deitel publications and services, visit www.deitel.com
Trang 28Using the UML 2 to Develop an Object-Oriented ATM Design xxvii
Optional Case Study: Using the UML 2 to Develop an Oriented ATM Design
Object-The optional Software Engineering Case Study in Chapters 25 and 26 presents a carefullypaced introduction to object-oriented design using the UML It will help you prepare forthe kinds of substantial projects you’ll encounter in industry We design and fully imple-ment the software for a simple automated teller machine (ATM) The case study has beenreviewed through many editions by a distinguished team of OOD/UML academics andindustry professionals, including leaders in the field from Rational (the creators of theUML) and the Object Management Group (responsible for evolving the UML)
We introduce a simple, concise subset of the UML, then guide you through a firstdesign experience intended for the novice The case study is not an exercise—it’s an end-to-end learning experience that concludes with a detailed walkthrough of the completeC++ code (850 lines)
At the end of Chapter 1, we introduce basic concepts and terminology of OOD InChapter 25, we analyze a typical requirements document that specifies a system to bebuilt, determine the objects needed to implement that system, determine the attributesthese objects need to have, determine the behaviors these objects need to exhibit, andspecify how the objects must interact with one another to meet the system requirements
In Chapter 26, we include a complete C++ code implementation of the ATM, using keyobject-oriented programming notions, including classes, objects, encapsulation, visibility,composition, inheritance and polymorphism
Companion Website
We include a set of free, web-based student supplements to the book—the CompanionWebsite—available with new books purchased from Pearson (see the scratch card at thefront of the book for your access code) To access the Companion Website, visitwww.pearsonhighered.com/deitel/ and select the Companion Website link in the sec-
tion for this book If the access code in front of your book is already redeemed, you can purchase access to this material directly from the Companion Website
The Companion Website contains the following chapters and appendices in able PDF format:
search-• Chapter 23, Boost Libraries, Technical Report 1 and C++0x
• Chapter 24, Other Topics
• Chapter 25, ATM Case Study, Part 1: Object-Oriented Design with the UML
• Chapter 26, ATM Case Study, Part 2: Implementing an Object-Oriented Design
• Chapter 27, Game Programming with Ogre
• Appendix F, C Legacy Code Topics
• Appendix G, UML 2: Additional Diagram Types
• Appendix H, Using the Visual Studio Debugger
• Appendix I, Using the GNU C++ Debugger
The Companion Website also includes:
• VideoNotes in which you can watch and listen as Paul Deitel shows you the portant features of the code examples in Chapters 2–13 and portions ofChapters 16 and 17
Trang 29im-• Two true/false questions per section with answers for self-review.
• Solutions to approximately half of the solved exercises in the book
The following additional materials are posted at both the Companion Website and atwww.deitel.com/books/cpphtp7/:
• An arrays of pointers to functions example and additional function pointer cises (from Chapter 8)
exer-• String Class Operator Overloading Case Study (from Chapter 11)
• Building Your Own Compiler exercise descriptions (from Chapter 20)
Dependency Chart
The chart on the next page shows the dependencies among the chapters to help instructors
plan their syllabi C++ How to Program, 7/e is appropriate for CS1 and CS2 courses.
Teaching Approach
C++ How to Program, 7/e, contains a rich collection of examples The book concentrates
on the principles of good software engineering and stresses program clarity We teach byexample We are educators who teach leading-edge programming languages and software-related topics in academic, government, military and industry classrooms worldwide
Live-Code Approach C++ How to Program, 7/e, is loaded with “live-code” examples Most
new concepts are presented in the context of complete working C++ applications, followed
by one or more executions showing program inputs and outputs
Syntax Coloring For readability, we syntax color all the C++ code, similar to the way most
C++ integrated-development environments and code editors syntax color code Our tax-coloring conventions are as follows:
syn-Code Highlighting We place yellow rectangles around key code segments.
Using Fonts for Emphasis We place the key terms and the index’s page reference for each
defining occurrence in bold maroon text for easy reference We emphasize on-screen ponents in the bold Helvetica font (e.g., the File menu) and C++ program text in the Lu- cida font (for example, int x = 5;)
com-Web Access All of the source-code examples are available for download from:
Quotations Each chapter begins with quotations We hope that you enjoy relating these
to the chapter material
Objectives The quotes are followed by a list of chapter objectives
Illustrations/Figures Abundant charts, tables, line drawings, UML diagrams, programs
and program output are included
comments appear in green
keywords appear in dark blue
errors appear in red
constants and literal values appear in light blue
all other code appears in black
www.deitel.com/books/cpphtp7/
www.pearsonhighered.com/deitel/
Trang 30Teaching Approach xxix
Introduction
1 Introduction to Computers, the Internet and the Web
Intro to Programming, Classes and Objects
2 Intro to C++ Programming
3 Intro to Classes and Objects
Control Statements, Methods and Arrays
4 Control Statements: Part 1
5 Control Statements: Part 2
6 Functions and an Intro to Recursion
7 Arrays and Vectors
Object-Oriented Programming Object-Oriented
Design with the UML
1 Most of Chapter 15 is readable after Chapter 7
A small portion requires Chapters 12 and 14.
[Note: Arrows pointing into a
chapter indicate that chapter’s
24 Other Topics
23 Boost Libraries, Technical Report 1 and C++0x
10 Classes: A Deeper Look, Part 2
14 Templates
9 Classes: A Deeper Look, Part 1
11 Operator Overloading
13 OOP: Polymorphism
12 OOP: Inheritance
16 Exception Handling
8 Pointers
21 Bits, Characters,
C-Strings and struct s
Legacy C Topics
Trang 31Programming 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 acombined seven decades of programming and teaching experience
Wrap-Up Section Each chapter ends with a recap of the chapter content, then transitions
to the next chapter
Summary Bullets We present a section-by-section bullet-list summary of the chapter Terminology We include an alphabetized list of the important terms defined in each chap-
ter with the page number of each term’s defining occurrence for easy reference
Self-Review Exercises and Answers Extensive self-review exercises and answers are
includ-ed for self study All of the exercises in the optional ATM case study are fully solvinclud-ed
Exercises Each chapter concludes with a substantial set of exercises including:
• simple recall of important terminology and concepts,
• identifying the errors in code samples,
• writing individual C++ statements,
• writing small portions of functions and classes,
• writing complete C++ functions, classes and programs, and
• major projects
Instructors can use these exercises to form homework assignments, short quizzes, major
ex-aminations and term projects [NOTE: Please do not write to us requesting access to the
Pearson Instructor’s Resource Center which contains the book’s instructor
supple-Good Programming Practice
The Good Programming Practices call attention to techniques that will help you duce programs that are clearer, more understandable and more maintainable. i.0
pro-Common Programming Error
Pointing out these Common Programming Errors reduces the likelihood that you’ll
Error-Prevention Tip
These tips contain suggestions for exposing and removing bugs from your programs; many describe aspects of C++ that prevent bugs from getting into programs in the first place. i.0
Performance Tip
These tips highlight opportunities for making your programs run faster or minimizing the
Portability Tip
The Portability Tips help you write code that will run on a variety of platforms. i.0
Software Engineering Observation
The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems. i.0
Trang 32Student Resources xxxi
ments, including the exercise solutions Access is limited strictly to college instructors teaching from the book Instructors may obtain access only through their Pearson rep-
resentatives Solutions are not provided for “project” exercises.] Check out our
Program-ming Projects Resource Center (www.deitel.com/ProgrammingProjects/) for lots ofadditional exercise and project possibilities
Index We’ve included an extensive index, which is especially useful when you use the
book as a reference Defining occurrences of key terms are highlighted with a bold maroon
page number
Student Resources
Many C++ development tools are available We wrote C++ How to Program, 7/e primarily
using Microsoft’s free Visual C++ Express Edition (which is available free for download atwww.microsoft.com/express/vc/) and the free GNU C++ (gcc.gnu.org/install/ binaries.html), which is already installed on most Linux systems and can be installed onMac OS X and Windows systems as well You can learn more about Visual C++ Express atmsdn.microsoft.com/vstudio/express/visualc You can learn more about GNU C++
at gcc.gnu.org Apple includes GNU C++ in their Xcode development tools, which Mac
OS X users can download from developer.apple.com/tools/xcode
For additional resources and software downloads see our C++ Resource Center:
For other C++ compilers that are available free for download:
CourseSmart Web Books
Today’s students and instructors have increasing demands on their time and money son has responded to that need by offering digital texts and course materials onlinethrough CourseSmart CourseSmart allows faculty to review course materials online sav-ing time and costs It is also environmentally sound and offers students a high-quality dig-ital version of the text for as much as 50% off the cost of a print copy of the text Studentsreceive the same content offered in the print textbook enhanced by search, note-taking,and printing tools For more information, visit www.coursesmart.com
Pear-Instructor Supplements
The following supplements are available to qualified instructors only through PearsonEducation’s Instructor Resource Center (www.pearsonhighered.com/irc):
• Solutions Manual with solutions to most of the end-of-chapter exercises and Lab
Manual exercises We’ve also graded the difficulty of each programming exercise
in the book, and have posted a file that assigns a grade level to each programmingexercise (in increasingly challenging order: 1, 2, 3 and Project)
• Test Item File of multiple-choice questions (approximately two per book section)
• Customizable PowerPoint® slides containing all the code and figures in the text,plus bulleted items that summarize the key points in the text
www.deitel.com/cplusplus/
www.thefreecountry.com/developercity/ccompilers.shtml
www.compilers.net/Dir/Compilers/CCpp.htm
Trang 33If you are not already a registered faculty member, contact your Pearson representative orvisit www.pearsonhighered.com/educator/replocator/.
Deitel® Buzz Online Free E-mail Newsletter
The Deitel ® Buzz Online e-mail newsletter will keep you posted about issues related to C++ How to Program, 7/e It also includes commentary on industry trends and develop-
ments, links to free articles and resources from our published books and upcoming cations, product-release schedules, errata, challenges, anecdotes, information on ourcorporate instructor-led training courses and more To subscribe, visit
publi-The Deitel Online Resource Centers
Our website www.deitel.com provides more than 100 Resource Centers on various topicsincluding programming languages, software development, Web 2.0, Internet business andopen-source projects—see the list of Resource Centers in the first few pages of this bookand visit www.deitel.com/ResourceCenters.html We’ve found many exceptional re-sources online, including tutorials, documentation, software downloads, articles, blogs,podcasts, videos, code samples, books, e-books and more—most of them are free Each
week we announce our latest Resource Centers in our newsletter, the Deitel ® Buzz Online.
Some of the Resource Centers you might find helpful while studying this book are C++,C++ Boost Libraries, C++ Game Programming, Visual C++, UML, Code Search Enginesand Code Sites, Game Programming and Programming Projects
Follow Deitel on Twitter and Facebook
To receive updates on Deitel publications, Resource Centers, training courses, partneroffers and more, follow us on Twitter®
and join the Deitel & Associates group on Facebook®
Acknowledgments
It’s a pleasure to acknowledge the efforts of people whose names do not appear on the
cov-er, but whose hard work, cooperation, friendship and understanding were crucial to thebook’s production Many people at Deitel & Associates, Inc., devoted long hours to thisproject—thanks especially to Abbey Deitel and Barbara Deitel
We would also like to thank the participants of our Honors Internship program whocontributed to this publication—Matthew Pearson, a Computer Science graduate of Cor-nell University; and Christine Chen, an Operations Research and Information Engi-neering major at Cornell University
We are fortunate to have worked on this project with the dedicated team of publishingprofessionals at Pearson We appreciate the efforts of Marcia Horton, Editorial Director
of Pearson’s Engineering and Computer Science Division, and Michael Hirsch, Chief of Computer Science Carole Snyder recruited the book’s review team and managedthe review process Francesco Santalucia (an independent artist) and Kristine Carney of
Editor-in-www.deitel.com/newsletter/subscribe.html
@deitel
http://www.deitel.com/deitelfan/
Trang 34About the Authors xxxiii
Pearson designed the book’s cover—we provided the concept, and they made it happen.Scott Disanno and Bob Engelhardt managed the book’s production Erin Davis and Mar-garet Waples marketed the book through academic and professional channels
C++ How to Program, 7/e Reviewers
We wish to acknowledge the efforts of our reviewers Adhering to a tight time schedule,they scrutinized the text and the programs and provided countless suggestions for improv-ing the accuracy and completeness of the presentation:
Academic Reviewers:
• Thomas J Borrelli (Rochester Institute of Technology)
• Peter J DePasquale (The College of New Jersey)
• Jack Hagemeister (Washington State University)
• Williams M Higdon (University of Indiana)
• Dean Mathias (Utah State University)
• Robert A McLain (Tidewater Community College)
• Dave Topham (Ohlone College)
Industry Reviewers:
• Chris Cox (Adobe Systems)
• Gregory Dai (Kernel Development)
• Doug Gregor (Apple, Inc.)
• April Reagan (Microsoft)
• José Antonio González Seco (Parliament of Andalusia, Spain)
Well, there you have it! Welcome to the exciting world of C++ and object-orientedprogramming We hope you enjoy this look at contemporary computer programming Asyou read the book, we would sincerely appreciate your comments, criticisms, correctionsand 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++ How to Program, Seventh Edition as much as we enjoyed
About the Authors
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.deitel@deitel.com
www.deitel.com/books/cpphtp7/
Trang 35Through Deitel & Associates, Inc., he has delivered C++, C, Java, C#, Visual Basic andInternet programming courses to industry clients, including Cisco, IBM, Sun Microsys-tems, Dell, Lucent Technologies, Fidelity, NASA at the Kennedy Space Center, the Na-tional Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software,Boeing, SunGard Higher Education, Stratus, Cambridge Technology Partners, Open En-vironment Corporation, One Wave, Hyperion Software, Adra Systems, Entergy, Cable-Data Systems, Nortel Networks, Puma, iRobot, Invensys and many more He holds theJava Certified Programmer and Java Certified Developer certifications and has been des-ignated by Sun Microsystems as a Java Champion He has also lectured on Java and C++for the Boston Chapter of the Association for Computing Machinery He and his co-author, Dr Harvey M Deitel, are the world’s best-selling programming-language text-book authors.
Dr Harvey M Deitel, Chairman and Chief Strategy Officer of Deitel & Associates,
Inc., has 48 years of academic and industry experience in the computer field Dr Deitelearned B.S and M.S degrees from MIT and a Ph.D from Boston University He hasextensive college teaching experience, including earning tenure and serving as theChairman of the Computer Science Department at Boston College before foundingDeitel & Associates, Inc., with his son, Paul J Deitel He and Paul are the co-authors ofdozens of books and multimedia packages and they are writing many more With transla-tions published in Japanese, German, Russian, Traditional Chinese, Simplified Chinese,Spanish, Korean, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish, the Dei-tels’ texts have earned international recognition Dr Deitel has delivered hundreds of pro-fessional seminars to major corporations, academic institutions, government organizationsand the military
About Deitel & Associates, Inc.
Deitel & Associates, Inc., is an internationally recognized authoring and corporate ing organization specializing in computer programming languages, Internet and web soft-ware technology, object-technology education and Internet business development Thecompany provides instructor-led courses delivered at client sites worldwide on majorprogramming languages and platforms, such as C++, Visual C++®, C, Java™, VisualC#®, Visual Basic®, XML®, Python®, object technology, Internet and web program-ming, and a growing list of additional programming and software-development-relatedcourses The founders of Deitel & Associates, Inc., are Paul J Deitel and Dr Harvey M.Deitel The company’s clients include many of the world’s largest companies, governmentagencies, branches of the military, and academic institutions Through its 33-year publish-ing partnership with Prentice Hall/Pearson, Deitel & Associates, Inc., publishes leading-
train-edge programming textbooks, professional books, interactive multimedia Cyber rooms, LiveLessons DVD-based and web-based video courses, and e-content for popular
Class-course-management systems Deitel & Associates, Inc., and the authors can be reached viae-mail at:
To learn more about Deitel & Associates, Inc., its publications and its Dive Into ® Series
Corporate Training curriculum delivered at client locations worldwide, visit:
deitel@deitel.com
www.deitel.com/training/
Trang 36About Deitel & Associates, Inc xxxv
and subscribe to the free Deitel ® Buzz Online e-mail newsletter at:
Individuals wishing to purchase Deitel books, and LiveLessons DVD and web-based
training courses can do so through www.deitel.com Bulk orders by corporations, the ernment, the military and academic institutions should be placed directly with Pearson.For more information, visit www.prenhall.com/mischtm/support.html#order
gov-www.deitel.com/newsletter/subscribe.html
Trang 38—Henry David Thoreau
Man is still the most extraordinary computer of all.
—John F Kennedy
O b j e c t i v e s
In this chapter you’ll learn:
■ Basic hardware and software concepts
■ Object-technology concepts, such as classes, objects, attributes, behaviors, encapsulation and inheritance
■ The different types of programming languages
■ A typical C++ program development environment
■ The history of the standard object-oriented system modeling language, the UML
industry-■ The history of the Internet and the World Wide Web, and the Web 2.0
phenomenon
■ To test-drive C++
applications in GNU C++ on Linux and Microsoft’s Visual C++® on Windows®
Trang 39Welcome to C++! We’ve worked hard to create what we hope you’ll find to be an mative, entertaining and challenging learning experience C++ is a powerful computerprogramming language that is appropriate for technically oriented people with little or noprogramming experience and for experienced programmers to use in building substantial
infor-information systems C++ How to Program, Seventh Edition, is an effective learning tool
for each of these audiences
The core of the book emphasizes achieving program clarity through the proven niques of object-oriented programming We teach C++ features in the context of completeworking C++ programs and show the outputs produced when those programs are run on
tech-a computer—we ctech-all this the live-code approach You may download the example
pro-grams from www.deitel.com/books/cpphtp7/
The early chapters introduce the fundamentals of computers, computer programmingand the C++ computer programming language, providing a solid foundation for thedeeper treatment of C++ in the later chapters
Most people are at least somewhat familiar with the exciting things computers do.Using this textbook, you’ll learn how to command computers to do those things Com-puters (often referred to as hardware) are controlled by software (i.e., the instructions youwrite to command the computer to perform actions and make decisions) C++ is one oftoday’s most popular software development languages This text provides an introduction
to programming in the version of C++ standardized in the United States through the
American National Standards Institute (ANSI) and worldwide through the efforts of the
International Organization for Standardization (ISO)
1.7 Machine Languages, Assembly
Languages and High-Level Languages
1.8 History of C and C++
1.9 C++ Standard Library
1.10 History of Java
1.11 Fortran, COBOL, Pascal and Ada
1.12 BASIC, Visual Basic, Visual C++, C#
and NET
1.13 Key Software Trend: Object Technology
1.14 Typical C++ Development Environment
1.15 Notes About C++ and C++ How to
Trang 401.2 Computers: Hardware and Software 3
Computer use is increasing in most fields of endeavor Computing costs havedecreased dramatically due to rapid developments in both hardware and software technol-ogies Computers that might have filled large rooms and cost millions of dollars a fewdecades ago can now be inscribed on silicon chips smaller than a fingernail, costing a fewdollars each Those large computers were called mainframes and current versions arewidely used today in business, government and industry Fortunately, silicon is one of themost abundant materials on earth—it’s an ingredient in common sand Silicon chip tech-nology has made computing so economical that more than a billion general-purpose com-puters are in use worldwide, helping people in business, industry and government, and intheir personal lives
Over the years, many programmers learned the programming methodology called
structured programming You’ll learn structured programming and an exciting newer methodology, object-oriented programming Why do we teach both? Object orientation
is the key programming methodology used by programmers today You’ll create and workwith many software objects in this text You’ll discover, however, that their internal struc-ture is often built using structured-programming techniques Also, the logic of manipu-lating objects is occasionally expressed with structured programming
To keep up to date with C++ developments at Deitel & Associates, please register for
our free e-mail newsletter, the Deitel ® Buzz Online, at
Please check out our growing list of C++ and related Resource Centers at
Some Resource Centers that will be valuable to you as you read this book are C++, VisualC++, C++ Game Programming, C++ Boost Libraries, Code Search Engines and CodeSites, Computer Game Programming, Programming Projects, Eclipse, Linux and OpenSource Each week we announce our latest Resource Centers in the newsletter Errata andupdates for this book are posted at
You are embarking on a challenging and rewarding path As you proceed, if you haveany questions, please send e-mail to
We’ll respond promptly We hope that you’ll enjoy learning with C++ How to Program, Seventh Edition
A computer is a device that can perform computations and make logical decisions billions
of times faster than human beings can For example, many of today’s personal computerscan perform several billion additions per second A person operating a desk calculatorcould spend an entire lifetime performing calculations and still not complete as many cal-culations as a powerful personal computer can perform in one second! (Points to ponder:How would you know whether the person added the numbers correctly? How would youknow whether the computer added the numbers correctly?) Today’s fastest supercomput-