Tải bản đầy đủ (.pdf) (817 trang)

Object Oriented Programming Using C++ ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.19 MB, 817 trang )

Object-Oriented
Programming
Using C++
Fourth Edition
Joyce Farrell
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
Object-Oriented Programming
Using C++, Fourth Edition
Joyce Farrell
Executive Editor: Marie Lee
Acquisitions Editor: Amy Jollymore
Managing Editor: Tricia Coia
Developmental Editor: Lisa Ruffolo
Editorial Assistant: Patrick Frank
Marketing Manager: Bryant Chrzan
Content Project Manager: Erin Dowler
Art Director: Bruce Bond
Manufacturing Coordinator:
Julio Esperas
Proofreader: Wendy Benedetto
Cover Designer: Bruce Bond
Cover Photo: © iStockphoto.com/
Storman
Compositor: International Typesetting
and Composition
© 2009 Course Technology, Cengage Learning
ALL RIGHTS RESERVED. No part of this work covered by the copyright
herein may be reproduced, transmitted, stored or used in any form or by
any means—graphic, electronic, or mechanical, including but not limited
to photocopying, recording, scanning, digitizing, taping, Web distribution,


information networks, or information storage and retrieval systems, except
as permitted under Section 107 or 108 of the 1976 United States
Copyright Act—without the prior written permission of the publisher.
For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
For permission to use material from this text or product,
submit all requests online at cengage.com/permissions
Further permissions questions can be e-mailed to

ISBN-13: 978-1-4239-0257-7
ISBN-10: 1-4239-0257-2
Course Technology
25 Thomson Place
Boston, MA 02210
USA
Cengage Learning is a leading provider of customized learning solutions with
office locations around the globe, including Singapore, the United Kingdom,
Australia, Mexico, Brazil, and Japan. Locate your local office at:
international.cengage.com/region
Cengage Learning products are represented in Canada by Nelson
Education, Ltd.
For your lifelong learning solutions, visit course.cengage.com
Purchase any of our products at your local college store or at our
preferred online store www.ichapters.com
Some of the product names and company names used in this book have
been used for identification purposes only and may be trademarks or
registered trademarks of their respective manufacturers and sellers.
Course Technology, a part of Cengage Learning, reserves the right to
revise this publication and make changes from time to time in its content
without notice.

Printed in the United States of America
1 2 3 4 5 6 7 12 11 10 09 08
BRIEF CONTENTS
PREFACE xvii
READ THIS BEFORE YOU BEGIN xxi
CHAPTER 1 AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING
AND C++ 1
CHAPTER 2 EVALUATING C++ EXPRESSIONS 51
CHAPTER 3 MAKING DECISIONS 81
CHAPTER 4 PERFORMING LOOPS 123
CHAPTER 5 UNDERSTANDING ARRAYS, STRINGS, AND POINTERS 165
CHAPTER 6 USING C++ FUNCTIONS 223
CHAPTER 7 USING CLASSES 283
CHAPTER 8 CLASS FEATURES AND DESIGN ISSUES 333
CHAPTER 9 UNDERSTANDING FRIENDS AND OVERLOADING OPERATORS 385
CHAPTER 10 UNDERSTANDING INHERITANCE 451
CHAPTER 11 USING TEMPLATES 501
CHAPTER 12 HANDLING EXCEPTIONS 557
CHAPTER 13 ADVANCED INPUT AND OUTPUT 615
CHAPTER 14 ADVANCED TOPICS 673
APPENDIX A GETTING STARTED WITH MICROSOFT VISUAL STUDIO 2008 731
APPENDIX B GETTING STARTED WITH OTHER C++ COMPILERS 737
APPENDIX C OPERATOR PRECEDENCE AND ASSOCIATIVITY 745
APPENDIX D FORMATTING OUTPUT 749
APPENDIX E GENERATING RANDOM NUMBERS 755
GLOSSARY 761
INDEX 777
iii
This page intentionally left blank
CONTENTS

PREFACE xvii
READ THIS BEFORE YOU BEGIN xxi
CHAPTER 1 AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING
AND C++ 1
THE TASK OF PROGRAMMING 2
PROGRAMMING UNIVERSALS 3
PROCEDURAL PROGRAMMING 5
Early Procedural Programs 5
Modularity and Abstraction 7
Encapsulation 10
OBJECT-ORIENTED PROGRAMMING 11
Objects and Classes 11
Inheritance 12
Polymorphism 13
GETTING STARTED IN THE C++ PROGRAMMING ENVIRONMENT 13
Creating a
main()Function 14
WORKING WITH VARIABLES AND THE
const QUALIFIER 16
The
int Data Type 18
The
char Data Type 18
The
bool Data Type 19
Floating-Point Data Types 19
Declaring Variables 19
The
const Qualifier 21
CREATING COMMENTS 22

ANSI/ISO STANDARD C++ 23
Using Libraries, Preprocessor Directives, and namespace 24
PRODUCING C++ OUTPUT 25
PROVIDING C++ INPUT 27
A FIRST LOOK AT DATA STRUCTURES AND CLASSES 29
YOU DO IT 32
Creating a Program That Displays Variable Values 32
Introducing Errors into a Program 34
Modifying a Program to Accept Input Values 35
Creating a Simple Structure 36
v
CONTENTS
CHAPTER SUMMARY 37
KEY TERMS 38
REVIEW QUESTIONS 43
EXERCISES 45
CASE PROJECT 1 48
CASE PROJECT 2 48
UP FOR DISCUSSION 49
CHAPTER 2 EVALUATING C++ EXPRESSIONS 51
USING C++ BINARY ARITHMETIC OPERATORS 52
Using Modulus 56
PRECEDENCE AND ASSOCIATIVITY OF ARITHMETIC OPERATIONS 58
SHORTCUT ARITHMETIC OPERATORS 59
Compound Assignment Operators 59
Increment and Decrement Operators 60
OTHER UNARY OPERATORS 61
EVALUATING BOOLEAN EXPRESSIONS 63
PERFORMING OPERATIONS ON STRUCT FIELDS 65
YOU DO IT 67

Using Arithmetic Operators 67
Using Prefix and Postfix Increment and Decrement Operators 68
Using Operators with
struct Fields 69
CHAPTER SUMMARY 71
KEY TERMS 71
REVIEW QUESTIONS 73
EXERCISES 75
CASE PROJECT 1 78
CASE PROJECT 2 78
UP FOR DISCUSSION 79
CHAPTER 3 MAKING DECISIONS 81
USING THE IF STATEMENT 82
The Single-Alternative
if 82
The Dual-Alternative
if 85
USING A NESTED
IF 87
AVOIDING COMMON PITFALLS WITH
IF STATEMENTS 89
Pitfall: Forgetting that C++ Comparisons are Case Sensitive 89
Pitfalls: Assuming that indentation has a logical purpose, adding
an Unwanted Semicolon, and Forgetting Curly Braces 90
vi
CONTENTS
Pitfall: Using = Instead of == 91
Pitfall: Making Unnecessary Comparisons 93
Pitfall: Creating Unreachable Code 94
USING THE

SWITCH STATEMENT 96
USING THE CONDITIONAL OPERATOR 99
USING THE LOGICAL AND AND OR OPERATORS 100
Using the Logical AND Operator 100
Using the Logical OR Operator 102
Pitfall: Using OR When You Mean AND 104
Combining AND and OR Selections 104
MAKING DECISIONS WITH STRUCTURE FIELDS 105
YOU DO IT 107
Using a Single-Alternative if 107
Using a Dual-Alternative
if 108
Using a Compound Condition and Nested
ifs 109
CHAPTER SUMMARY 111
KEY TERMS 112
REVIEW QUESTIONS 113
EXERCISES 117
CASE PROJECT 1 121
CASE PROJECT 2 121
UP FOR DISCUSSION 122
CHAPTER 4 PERFORMING LOOPS 123
THE while LOOP 124
WRITING TYPICAL LOOPS 127
A Typical Loop: Input Verification 127
A Typical Loop: Reading Input Records 128
AVOIDING COMMON PITFALLS WITH LOOPS 130
Pitfall: Adding an Unwanted Semicolon 131
Pitfalls: Forgetting Curly Braces or Forgetting to Alter a Loop Control Variable 132
Pitfall: Failing to Initialize a Loop Control Variable 133

ACCUMULATING TOTALS 135
THE
FOR LOOP 136
PRETEST VS. POSTTEST LOOPS 139
NESTED LOOPS 143
USING LOOPS WITH STRUCTURE FIELDS 145
YOU DO IT 149
Using a Loop to Validate User Data Entry 149
Using a Structure in an Application Containing Several Loops 150
vii
CONTENTS
CHAPTER SUMMARY 154
KEY TERMS 155
REVIEW QUESTIONS 155
EXERCISES 159
CASE PROJECT 1 161
CASE PROJECT 2 162
UP FOR DISCUSSION 163
CHAPTER 5 UNDERSTANDING ARRAYS, STRINGS, AND POINTERS 165
UNDERSTANDING MEMORY ADDRESSES 166
UNDERSTANDING ARRAYS 167
STORING VALUES IN AN ARRAY 170
ACCESSING AND USING ARRAY VALUES 172
AVOIDING COMMON ARRAY ERRORS 175
Pitfall: Forgetting that Arrays are Zero-Based 175
Pitfall: Accessing Locations Beyond the Array 176
USING PART OF AN ARRAY 177
USING PARALLEL ARRAYS 180
CREATING ARRAYS OF STRUCTURE OBJECTS 183
USING TWO-DIMENSIONAL ARRAYS 185

USING CHARACTER ARRAY STRINGS 188
Strings Created as Arrays of Characters 189
Special String-Handling Problems When Using
Character Arrays 190
AN INTRODUCTION TO THE
STRING CLASS 197
USING POINTERS 200
USING A POINTER INSTEAD OF AN ARRAY NAME 201
YOU DO IT 205
Using an Array 205
Understanding Memory Addresses 208
CHAPTER SUMMARY 210
KEY TERMS 211
REVIEW QUESTIONS 212
EXERCISES 215
CASE PROJECT 1 220
CASE PROJECT 2 220
UP FOR DISCUSSION 221
viii
CONTENTS
CHAPTER 6 USING C++ FUNCTIONS 223
WRITING SIMPLE FUNCTIONS 224
PLACING FUNCTIONS WITHIN FILES 226
Placing a Function as Part of the Same File, Before
main() 226
Placing a Function as Part of the Same File, After
main() 228
Placing a Function in Its Own File 230
UNDERSTANDING PROCEDURAL ABSTRACTION 232
UNDERSTANDING SCOPE 234

Distinguishing Between Local and Global Variables 234
Using the Scope Resolution Operator 237
RETURNING VALUES FROM FUNCTIONS 239
PASSING VALUES TO FUNCTIONS 243
AVOIDING COMMON ERRORS WHEN USING FUNCTIONS 246
Pitfall: Neglecting to Make Sure the Function Declaration, Header, and Call Agree 246
Pitfall: Indicating an Argument Type in a Function Call 247
Pitfall: Indicating a Return Type in a Function Call 247
Pitfall: Ignoring the Order of Parameters 247
Pitfall: Assuming that an Unused Return Value Has an Effect 248
USING OBJECTS AS PARAMETERS TO,
AND AS RETURN TYPES OF, FUNCTIONS 248
PASSING ADDRESSES TO FUNCTIONS 250
USING REFERENCE VARIABLES WITH FUNCTIONS 253
Declaring Reference Variables 253
Passing Variable Addresses to Reference Variables 255
PASSING ARRAYS TO FUNCTIONS 258
USING INLINE FUNCTIONS 260
USING DEFAULT PARAMETERS 262
OVERLOADING FUNCTIONS 264
Avoiding Ambiguity 266
YOU DO IT 267
Writing Functions That Return Values 267
Writing a Function That Requires a Parameter 269
CHAPTER SUMMARY 270
KEY TERMS 271
REVIEW QUESTIONS 273
EXERCISES 276
CASE PROJECT 1 281
CASE PROJECT 2 281

UP FOR DISCUSSION 282
ix
CONTENTS
CHAPTER 7 USING CLASSES 283
CREATING CLASSES 284
ENCAPSULATING CLASS COMPONENTS 286
Designing Classes 287
IMPLEMENTING FUNCTIONS IN A CLASS 289
Using Public Functions to Alter Private Data 290
UNUSUAL USE: USING PRIVATE FUNCTIONS AND PUBLIC DATA 295
CONSIDERING SCOPE WHEN DEFINING MEMBER FUNCTIONS 298
USING STATIC CLASS MEMBERS 301
Defining Static Data Members 301
Using Static Functions 305
UNDERSTANDING THE
THIS POINTER 307
Using the
this Pointer Explicitly 311
Using the Pointer-to-Member Operator 311
UNDERSTANDING POLYMORPHISM 313
YOU DO IT 314
Creating and Using a Class 314
Using a
static Field 317
Understanding How
static and Non-static Fields are Stored 320
CHAPTER SUMMARY 321
KEY TERMS 322
REVIEW QUESTIONS 323
EXERCISES 327

CASE PROJECT 1 330
CASE PROJECT 2 331
UP FOR DISCUSSION 331
CHAPTER 8 CLASS FEATURES AND DESIGN ISSUES 333
CLASSIFYING THE ROLES OF MEMBER FUNCTIONS 334
UNDERSTANDING CONSTRUCTORS 335
WRITING CONSTRUCTORS WITHOUT PARAMETERS 336
WRITING CONSTRUCTORS WITH PARAMETERS 341
Pitfall: Using Parentheses When Instantiating an Object with a Default Constructor 344
OVERLOADING CONSTRUCTORS 345
USING DESTRUCTORS 347
UNDERSTANDING COMPOSITION 352
Using Composition When Member Classes Contain Non-default Constructors 355
USING #IFNDEF, #DEFINE, AND #ENDIF 358
IMPROVING CLASSES 361
x
CONTENTS
Selecting Member Data and Function Names 361
Reducing Coupling Between Functions 363
Increasing Cohesion in a Function 363
YOU DO IT 365
Creating a Class with a Constructor 365
Using Constructor Parameters 368
Understanding Composition 369
CHAPTER SUMMARY 372
KEY TERMS 374
REVIEW QUESTIONS 375
EXERCISES 378
CASE PROJECT 1 382
CASE PROJECT 2 383

UP FOR DISCUSSION 384
CHAPTER 9 UNDERSTANDING FRIENDS AND OVERLOADING OPERATORS 385
WHAT ARE FRIENDS? 386
HOW TO DECLARE A FUNCTION AS A FRIEND 387
UNDERSTANDING THE BENEFITS OF OVERLOADING AND POLYMORPHISM 391
USING A
FRIEND FUNCTION TO ACCESS DATA FROM TWO CLASSES 393
Using a Forward Declaration 395
OVERLOADING OPERATORS—THE GENERAL RULES 397
OVERLOADING AN ARITHMETIC OPERATOR 402
Paying Attention to the Order of the Operands 405
OVERLOADING AN OPERATOR TO WORK WITH
AN OBJECT AND A PRIMITIVE TYPE 406
USING MULTIPLE OPERATIONS IN AN EXPRESSION 409
OVERLOADING OUTPUT 412
OVERLOADING INPUT 416
OVERLOADING THE PREFIX ++ AND – – OPERATORS 418
USING POSTFIX INCREMENT AND DECREMENT OPERATORS 421
OVERLOADING THE == OPERATOR 422
OVERLOADING THE = OPERATOR 424
OVERLOADING [ ] AND ( ) 430
YOU DO IT 434
Overloading an Arithmetic Operator 434
Overloading an Output Operator 435
CHAPTER SUMMARY 436
KEY TERMS 438
xi
CONTENTS
REVIEW QUESTIONS 439
EXERCISES 442

CASE PROJECT 1 447
CASE PROJECT 2 448
UP FOR DISCUSSION 449
CHAPTER 10 UNDERSTANDING INHERITANCE 451
UNDERSTANDING INHERITANCE 452
UNDERSTANDING THE ADVANTAGES PROVIDED BY INHERITANCE 453
CREATING A DERIVED CLASS 454
UNDERSTANDING INHERITANCE RESTRICTIONS 458
CHOOSING THE CLASS ACCESS SPECIFIER 462
OVERRIDING INHERITED ACCESS 463
OVERRIDING AND OVERLOADING PARENT CLASS FUNCTIONS 467
PROVIDING FOR BASE CLASS CONSTRUCTION 474
USING MULTIPLE INHERITANCE 478
DISADVANTAGES OF USING MULTIPLE INHERITANCE 481
USING VIRTUAL BASE CLASSES 482
YOU DO IT 484
Creating a Base Class 484
Creating a Child Class 486
Creating Another Child Class 488
Using Multiple Inheritance 489
CHAPTER SUMMARY 491
KEY TERMS 492
REVIEW QUESTIONS 493
EXERCISES 496
CASE PROJECT 1 498
CASE PROJECT 2 499
UP FOR DISCUSSION 500
CHAPTER 11 USING TEMPLATES 501
UNDERSTANDING THE USEFULNESS OF FUNCTION TEMPLATES 502
CREATING FUNCTION TEMPLATES 504

USING MULTIPLE PARAMETERS IN FUNCTION TEMPLATES 506
OVERLOADING FUNCTION TEMPLATES 509
USING MORE THAN ONE TYPE IN A FUNCTION TEMPLATE 511
USING MORE THAN ONE PARAMETERIZED TYPE IN A FUNCTION TEMPLATE 513
xii
CONTENTS
EXPLICITLY SPECIFYING THE TYPE IN A FUNCTION TEMPLATE 516
Using Multiple Explicit Types in a Function Template 518
USING CLASS TEMPLATES 519
CREATING A COMPLETE CLASS TEMPLATE 521
UNDERSTANDING THE USEFULNESS OF CONTAINER CLASSES 523
CREATING AN
ARRAY TEMPLATE CLASS 525
INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY 531
Inserting a New Element into a Vector Using Iterators and the
insert()Method 536
Sorting Vector Elements Using the
sort()Algorithm 536
YOU DO IT 540
Creating a Function Template 540
Proving the Template Function Works with Class Objects 541
CHAPTER SUMMARY 544
KEY TERMS 546
REVIEW QUESTIONS 547
EXERCISES 550
CASE PROJECT 1 553
CASE PROJECT 2 554
UP FOR DISCUSSION 555
CHAPTER 12 HANDLING EXCEPTIONS 557
UNDERSTANDING THE LIMITATIONS OF TRADITIONAL ERROR HANDLING METHODS 558

THROWING EXCEPTIONS 560
USING
TRY BLOCKS 563
CATCHING EXCEPTIONS 564
USING MULTIPLE
THROW STATEMENTS AND MULTIPLE CATCH BLOCKS 566
Determining the Order of
catch Blocks 568
USING THE DEFAULT EXCEPTION HANDLER 569
UNDERSTANDING EXCEPTION CLASSES IN THE STANDARD RUNTIME LIBRARY 570
An Example of an Automatically Thrown
logic_error 571
Using the
what()Function 573
Explicitly Throwing a Built-in
exception 573
DERIVING YOUR OWN EXCEPTIONS FROM THE
EXCEPTION CLASS 576
Overriding the Exception Class
what()Function 580
USING EXCEPTION SPECIFICATIONS 582
Exception Specifications in ANSI C++ 582
How Visual C++ Departs from the ANSI Standard 583
UNWINDING THE STACK 583
RETHROWING EXCEPTIONS 589
xiii
CONTENTS
HANDLING MEMORY ALLOCATION EXCEPTIONS 591
WHEN TO USE EXCEPTION HANDLING 593
YOU DO IT 594

Creating a Typical Data Entry Application 594
Modifying the
SimpleDataEntry Program to Throw an Exception 595
Creating a Custom Exception Class 597
Throwing and Catching Multiple Exceptions 599
Using a Generic
catch Block 602
CHAPTER SUMMARY 603
KEY TERMS 605
REVIEW QUESTIONS 606
EXERCISES 609
CASE PROJECT 1 613
CASE PROJECT 2 613
UP FOR DISCUSSION 614
CHAPTER 13 ADVANCED INPUT AND OUTPUT 615
UNDERSTANDING CIN AND COUT AS OBJECTS 616
USING
ISTREAM MEMBER FUNCTIONS 618
Using the
get()Function 618
Using the
ignore()Function 621
Using the
getline()Function 623
Other
istream Member Functions 624
USING
OSTREAM MEMBER FUNCTIONS 625
Using Format Flags with
setf()and unsetf() 625

Using the
width()Function 626
Using the
precision()Function 627
Other
ostream Member Functions 627
USING MANIPULATORS 628
Using the
setprecision()Manipulator 629
Using the
setw()Manipulator 630
Using the
setiosflags() and resetiosflags()Manipulators 631
Using the
oct, hex, and showbase manipulators 631
CREATING MANIPULATOR FUNCTIONS 632
UNDERSTANDING COMPUTER FILES 634
SIMPLE FILE OUTPUT 636
SIMPLE FILE INPUT 642
WRITING AND READING OBJECTS 644
WORKING WITH RANDOM ACCESS FILES 648
Setting up a File for Direct Access 650
xiv
CONTENTS
xv
Writing Records to a File Randomly 652
Randomly Reading the File 653
YOU DO IT 655
Using
stream Functions and Manipulators 655

Creating a Manipulator 657
Writing to and Reading from a File 658
CHAPTER SUMMARY 660
KEY TERMS 662
REVIEW QUESTIONS 664
EXERCISES 667
CASE PROJECT 1 669
CASE PROJECT 2 670
UP FOR DISCUSSION 671
CHAPTER 14 ADVANCED TOPICS 673
USING ENUMERATIONS 674
UNDERSTANDING THE BINARY SYSTEM 676
UNDERSTANDING WHY COMPUTERS USE THE BINARY SYSTEM 679
USING INDIVIDUAL BITS TO STORE DATA 681
CONVERTING A GROUP OF BIT FIELDS TO AN INTEGER VALUE 684
USING THE BITWISE
AND OPERATOR WITH A MASK 691
USING THE BITWISE INCLUSIVE OR OPERATOR 696
SHIFTING BITS 702
UNDERSTANDING RECURSION 704
USING A RECURSIVE FUNCTION TO SORT A LIST 708
YOU DO IT 712
Working with an Enumeration 712
Working with Bits 713
Using a Multi-Bit Field 715
Using a Mask to Convert Letters from Lowercase
to Uppercase 716
Working with Recursion 717
CHAPTER SUMMARY 719
KEY TERMS 720

REVIEW QUESTIONS 721
EXERCISES 724
CASE PROJECT 1 728
CASE PROJECT 2 728
UP FOR DISCUSSION 729
CONTENTS
APPENDIX A GETTING STARTED WITH MICROSOFT VISUAL STUDIO 2008 731
APPENDIX B GETTING STARTED WITH OTHER C++ COMPILERS 737
APPENDIX C OPERATOR PRECEDENCE AND ASSOCIATIVITY 745
APPENDIX D FORMATTING OUTPUT 749
APPENDIX E GENERATING RANDOM NUMBERS 755
GLOSSARY 761
INDEX 777
xvi
PREFACE
Object-Oriented Programming Using C++, Fourth Edition is designed for many levels of programming stu-
dents and a variety of programming teaching styles. Readers who are new to programming will find the
basics of programming logic and the C++ programming language covered thoroughly and clearly.
Comprehensive, engaging explanations, multiple programming examples, and step-by-step programming
lessons provide beginning readers with a solid C++ background. Users who know some C++ syntax, but are
new to object-oriented programming, will find objects explored thoroughly from the first chapters. Objects
are introduced early, so those who want to learn objects at the start of their programming experience can
do so. Users who want to postpone objects can simply omit the later sections of each chapter and cover the
basic programming structures with simple data types before returning to the more complex objects later on.
ORGANIZATION AND COVERAGE
Object-Oriented Programming Using C++ contains 14 chapters and five appendices that present clear text
explanations, directed hands-on instruction, and a wealth of exercises. In these chapters, readers learn
about programming logic in general, C++ syntax in particular, and gain an appreciation for and under-
standing of the object-oriented approach. When readers complete the book, they will have an under-
standing of object-oriented concepts as they apply to programming, and the ability to use these concepts

to develop C++ programs.
Chapter 1 provides an overview of programming in general and C++ in particular. You work with vari-
ables, comments, input and output, and data structures. This book distinguishes itself from other C++
books by introducing structure objects in Chapter 1 so that students start thinking in an object-oriented
manner from the beginning of the course.
Chapter 2 focuses on evaluating C++ expressions. Chapters 3, 4, and 5 discuss decisions, loops, arrays,
strings, and pointers—all fundamental building blocks of C++ programs. Chapter 6 provides a solid foun-
dation in writing and using functions including passing parameters by value and by reference and return-
ing values from functions.
Once students understand C++ basics they are ready for Chapters 7 and 8, which delve more completely
into the object-oriented aspects of C++, featuring classes, objects, and design issues. Friend functions and
operator overloading are covered in Chapter 9, and inheritance, another important OO feature, is explained
in Chapter 10.
Advanced C++ features such as templates, exception handling, and advanced input and output techniques,
including writing objects to files, are covered in Chapters 11, 12, and 13. Chapter 14 presents some inter-
esting adjuncts to C++ that make it such a powerful language, including creating enumerations, working
with bits, and understanding recursion.
Five appendices offer further explanation to topics mentioned in the chapters. Appendices A and B describe
how to get started with various C++ compilers. Appendix C contains a handy table of precedence and
associativity. Appendix D contains information on formatting output, and Appendix E is a lesson in
generating random numbers—an important skill in creating scientific simulations and games.
xvii
PREFACE
APPROACH
Object-Oriented Programming Using C++ teaches object-oriented concepts using C++ as a tool to demonstrate
these concepts. This book teaches programming concepts using a task-driven rather than a command-driven
approach. Structures are introduced in Chapter 1 so that students start thinking about objects right from
the start. However, discussion of objects is reserved for the last sections of the first six chapters, so that
instructors who prefer to start with a procedural approach can omit these sections at first, then go back
to cover them after the first six chapters have been completed.

FEATURES
Object-Oriented Programming Using C++ is an exceptional textbook because it also includes the following
features:
» Objectives. A brief list of objectives appears at the beginning of each chapter so the student has an
overview of the main topics to be covered.
» Notes. These provide additional information about a procedure or topic, such as an alternative method
of performing a procedure.
» Figures. Each chapter averages over 35 figures that contain diagrams, code, working programs, or
screen shots of the programs’ execution.
» Color. Besides adding visual interest to the text, the new two-color design is used to highlight C++
keywords each time they appear in a figure.
» Don’t Do It Icon. It is sometimes illustrative to show an example of how NOT to do something—for
example, having a dead code path in a program. However, students do not always read carefully and
sometimes use logic similar to that shown in what is intended to be a “bad” example. When the
instructor is critical, the frustrated student says, “But that’s how they did it in the book!” Therefore,
although the text will continue to describe bad examples, and the captions for the related figures
will mention that they are bad examples, the book also includes a “Don’t Do It” icon near the offend-
ing section of logic. This icon provides a visual jolt to the student, emphasizing that particular figures
are NOT to be emulated.
» Section Quiz. “Two truths and a lie” appears after each chapter section, with answers provided.
This quiz contains three statements from the preceding section of text—two true and one false. Over
the years, students have requested answers to problems, but we have hesitated to distribute them
in case instructors want to use problems as assignments or test questions. These true-false mini-
quizzes provide students with immediate feedback as they read, without “giving away” answers to
the existing multiple choice and programming problem questions.
» You Do It. After students study each chapter’s concepts, they are invited to create small applications
that illustrate the concepts. Each application is explained step-by-step as the students add appropriate
code to interesting applications.
» Summaries. A summary that recaps the programming concepts and commands covered follows
each chapter.

» Key Terms. Each chapter contains a list of all the key terms defined in the chapter, along with
explanations and presented in the order covered in the chapter. The list of Key Terms serves as an
additional chapter summary.
xviii
NEW!
NEW!
NEW!
PREFACE
» Review Questions. Each chapter includes 20 multiple choice review questions that test students’
understanding of what they learned in the chapter.
» Programming Exercises. Each chapter contains interesting exercises that provide students with
the opportunity to apply the concepts they have mastered by writing C++ programs.
» Gaming Exercises. In addition to many business-oriented programming exercises at the end of each
chapter, most chapters now also contain at least one game-oriented exercise.
» Debugging Exercises. Each chapter ends with debugging exercises—programs with a few syntax
or logical errors. The student can find the errors and fix them, developing crucial skills of reading
others’ programs, analyzing error messages and probable cause of errors, and solving problems.
» Running Case. The book contains two running cases in which the student develops large classes,
adding appropriate features as each new concept is introduced. By the end of the book, the student
has created two substantial working classes.
» Up For Discussion. Each chapter ends with open-ended, frequently thought-provoking questions
that are appropriate for classroom or online discussion sessions.
» Syntax Improvements. Three minor, but important improvements have been made in the C++ syn-
tax shown throughout the book. First, the
main()function of a program always returns 0, consistent
with common business and ANSI standards. Second, spaces have been inserted surrounding all the
insertion and extraction operators, making code easier to read. Third, the asterisks for pointers and
the ampersands for references are shown next to the data type in declarations, with a space follow-
ing. For example :
int* ptr;. This makes it clearer that the data type of ptr is int pointer.

» Glossary. All of the Key Terms presented at the end of each chapter are listed in alphabetical order
in a Glossary at the end of the book.
INSTRUCTOR RESOURCES
The following supplemental materials are available when this book is used in a classroom setting. All of
the instructor resources for this book are provided to the instructor on a single CD-ROM.
Electronic Instructor’s Manual. The Instructor’s Manual that accompanies this textbook includes
additional instructional material to assist in class preparation, including suggestions for lecture topics.
ExamView
®
. This textbook is accompanied by ExamView, a powerful testing software package that
allows instructors to create and administer printed, computer (LAN-based), and Internet exams.
ExamView includes hundreds of questions that correspond to the topics covered in this text, enabling
students to generate detailed study guides that include page references for further review. The computer-
based and Internet testing components allow students to take exams at their computers, and save the
instructor time by grading each exam automatically.
PowerPoint Presentations. This book comes with Microsoft PowerPoint slides for each chapter. These
slides are included as a teaching aid for classroom presentation; teachers can make them available on the
network for chapter review, or print them for classroom distribution. Instructors can add their own slides
for additional topics they introduce to the class.
Solution Files. Password-protected solutions to all “You Do It” exercises and end-of-chapter exercises
are provided on the Instructor Resources CD-ROM and on the Course Technology Web site at
www.course.com.
xix
NEW!
NEW!
NEW!
PREFACE
xx
Distance Learning. Course Technology is proud to present online test banks in WebCT and Blackboard
to provide the most complete and dynamic learning experience possible. Instructors are encouraged to

make the most of the course, both online and offline. For more information on how to access the online
test bank, contact your local Course Technology sales representative.
ACKNOWLEDGMENTS
Thank you to all the people who support me while I write and who make this book the best it can be.
Thanks especially to Lisa Ruffolo, my Developmental Editor, who not only edits, but acts as my cheer-
leader, and to Tricia Coia, Managing Editor, who makes every part of the process work together. Thank
also to Amy Jollymore, Acquisitions Editor, who has brought innovation and energy to the publishing
process. Thanks to Erin Dowler, Content Project Manager, and to Deepti Narwat, full service representa-
tive. Thanks to Serge Palladino, Quality Assurance Tester, whose attention to detail has guaranteed that
this is a quality textbook. Thank you to the reviewers who provided helpful and insightful comments
during the development of this book, including Steve Chadwick, Embry-Riddle Aeronautical University;
Robert Dollinger, University of Wisconsin Stevens Point; and Catherine Wyman, DeVry University.
Thank you to my husband Geoff for whom I am more grateful every day.
Finally, this book is dedicated to Rich and Sue in honor of their 30
th
wedding anniversary.
READ THIS BEFORE
YOU BEGIN
TO THE USER
DATA FILES
To complete some of the steps and exercises in this book, you will need data files that have been created
for this book. Your instructor will provide the data files to you. You also can obtain the files electronically
from the Course Technology Web site by connecting to www.course.com and then searching for this book
by title, author, or ISBN.
Each chapter in this book has its own set of data files, stored in a separate folder. For example, the files
for Chapter 3 are stored in the Chapter03 folder. You can use a computer in your school lab or your own
computer to complete the labs and exercises in this book.
USING YOUR OWN COMPUTER
To use your own computer to complete the steps and exercises in this book, you will need the
following:

» A personal computer. This book was written and quality assurance tested using Microsoft Vista
Professional.
» A C++ compiler. Almost all examples in this book will work with any C++ compiler. This book was
written using Microsoft Visual Studio 2008 Express Edition and quality assurance tested using
Microsoft Visual Studio 2008 Professsional. Appendix A contains instructions on getting started
with Microsoft Visual Studio 2008. Appendix B contains instructions on getting started with some
other compilers and suggests minor modifications you might have to make to your programs to get
them to work correctly using different compilers. If your book came with a copy of Microsoft Visual
Studio 2008 (Express or Professional), then you may install that on your computer and use it to
complete the material.
» Data files. You will not be able to complete the steps and exercises in this book using your own com-
puter unless you have the data files. You can get the data files from your instructor, or you can obtain
the data files electronically from the Course Technology Web site by connecting to www.course.com
and then searching for this book title.
TO THE INSTRUCTOR
To complete the labs and exercises in this book, your students must use a set of data files. These files are
included on the Instructor Resource CD-ROM. They may also be obtained electronically through the
Course Technology Web site at www.course.com. Follow the instructions in the Help file to copy the data
xxi
READ THIS BEFORE YOU BEGIN
xxii
files to your server or standalone computer. You can view the Help file using a text editor such as Notepad.
Once the files are copied, you should instruct your users how to copy the files to their own computers
or workstations.
COURSE TECHNOLOGY DATA FILES
You are granted a license to copy the data files to any computer or computer network used by individuals
who have purchased this book.
CHAPTERONE
AN OVERVIEW OF
OBJECT-ORIENTED

PROGRAMMING AND C++
1
1
»
In this chapter, you will:
Learn about the task of programming
Examine programming universals
Explore procedural programming
Be introduced to object-oriented programming
Get started in the C++ programming environment
Work with variables and the
const qualifier
Create comments
Examine the differences between ANSI/ISO C++ and
Standard C++
Produce C++ output with
cout
Provide input with cin
Begin to work with data structures and classes
AN OVERVIEW OF OBJECT-ORIENTED PROGRAMMING AND C++
2
Whether you are new to programming or have already had a class in logic or a programming
language other than C++, this chapter introduces you to the fundamental concepts of pro-
gramming, including procedural and object-oriented programming. After learning or review-
ing what it means to program, you will examine the characteristics of procedural programs
and consider a few examples. Then you will compare procedural and object-oriented
programs and learn the additional features object-orientation provides.
In the rest of the chapter, you will consider the basic principles behind object-oriented pro-
gramming techniques, including objects, classes, inheritance, and polymorphism. Then you
will get started in the C++ programming environment by applying what you have learned. For

example, you will learn how to create a
main()function, work with variables and constants,
and create comments. Finally, you will learn how to produce output and process input with
C++, and how to create your first objects.
THE TASK OF PROGRAMMING
Programming a computer involves writing instructions that enable a computer to carry out a single
task or a group of tasks. Writing these sets of instructions, which are known as programs or soft-
ware, requires using a computer programming language and resolving any errors in the instructions
so that the programs work correctly. Programs are also frequently called application programs,
or simply applications, because you apply them to a task such as preparing payroll checks,
creating inventory reports, or—as in the case of game programs—even entertaining someone.
As with any language, learning a computer programming language requires learning both vocab-
ulary and syntax. People speak a variety of languages, such as English and Japanese; similarly, pro-
grammers use many different programming languages, including Java, Visual Basic, C#, and C++.
The rules of any language make up its syntax. Writing in a programming language requires
correct use of that language’s syntax. In English, using incorrect syntax—that is, committing
a syntax error—might make communication more difficult but usually does not prevent it
altogether. If you ask, “Name yours what is?” most people can still figure out what you mean.
If you are vague or spell a word wrong when writing, most people will nevertheless understand
your message. Computers are not nearly as flexible as most people. As a result, using correct
syntax in a computer program is not just important—it’s essential.
Most of today’s programming languages follow syntax rules that are close enough to human
language to make them accessible to anyone willing to learn and practice them. When you
write programs, you write program statements that are instructions that are similar to
English-language sentences. The statements you write in a programming language must be
subsequently translated into machine language. Machine language is the language that com-
puters can understand; it consists of 1s and 0s. A translator program (called either a compiler
or an interpreter) checks your program for syntax errors. If there are no errors, the translator
changes your written program statements into machine language. Therefore, syntax errors
are not a big problem; you always have an opportunity to fix them before you actually attempt

to run the program. For example, if you write a computer program in C++ but spell a word
incorrectly or reverse the required order of two words, the compiler informs you of such
errors and will not let you run the program until you have corrected them.

×