Tải bản đầy đủ (.pdf) (1,337 trang)

Starting out with c++ early objects

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 (15.53 MB, 1,337 trang )


Unprecedented Praise for

Starting Out with C++

I want to tell you that I believe your C++ text is the most
thorough one available. I have used 5 different ones since
1992 and every one assumes the students know things that
they do not. You cover every detail. Thank you.
—David McLeod, Belmont Technical College, OH
The students have found your book to be easy to read and
understand—a great accomplishment.
—Al Cawns, Webster University, MO
I listen to what students say about the books I select. Their
response to Gaddis is unusually positive. They really like
the book.
—Jeffrey A. Kent, Los Angeles Valley College, CA
Greetings, I’m using your book in an introductory course in
C++ at University of Texas at Dallas. Your book is GREAT!!
It abstracts the complexity of C++ down to the core con-
cepts that we can build on. Thanks!
—Jim Burke, student
…just wanted to tell you that your book has made a lot of
difference in my life. Your book is absolutely “Awesome.”
You have a lot of examples in the book which help a lot.
Thanks again!
—Saud Faisal, student
I have adopted and am currently teaching from the Gaddis
second edition textbook. This is by far the best C++ book
that I have taught with.
—Deedee Herrera, Dodge City CC, KS


I like it better than the one we are using for our second
semester C++ course.
—Dr. Ron Bass, Austin Community College, TX
I took a good look at your 2nd edition as I revised my class
to use it and I think you did a super job. Moving recursion
and splitting the chapter on arrays made a great book even
better. Congratulations!
—Carol Schwab, Webster University, MO
I have adopted this book for courses at both Inver Hills
Community College and Century College in Minnesota this
semester. I have not been disappointed. It works for me.
—Ray Larson, Century College, MN
This book is very, very exhaustive in its coverage. I didn’t
even go through a part of it. But aside from its bulk, it was a
very good introduction to programming. Gaddis does an
excellent job of showing how to program step-by-step, and
makes it easy to teach yourself.
The book also contains a quick reference section where
you can look up frequently used commands without having
to find them in the text. This book is highly recommended
for beginning (and even continuing) programmers.
—Reviewer from The University of Texas at Dallas
Learned quite a bit from this textbook needed for my C++
class in college. I was pleasantly surprised at how well writ-
ten this book was, considering the topic it is covering. Great
Book! I’m keeping mine seeing as it will come in handy with
my future programming endeavors. Too bad other text-
books aren’t as well written.
—Craig Croteau, Dunedin, FL
I used this book for the first semester of college C++. It is an

excellent textbook. Some C++ textbooks have large amounts
of text with few examples, making them very hard to read
and understand.
This book is filled with examples in short sections about
specific C++ elements. I have kept it as a reference as infor-
mation is easy to find and the examples make it easy to
understand and implement.
I have two other books on C++, but if I were teaching a
C++ class, I would use this book.
—Karen Ryberg, Bismarck, ND

GaddA2005.book Page i Friday, September 16, 2005 11:52 AM

The book itself is fantastic. Everything is laid out in an easy
to read fashion. Truly a C++ beginners book.…Thanks for
writing a book that was so educational Tony!
—Student from Dover, NH
This book is just amazing.…It goes in-depth on almost
everything in C++. It’ll teach you pretty much everything
you need except the most advanced topics. Its a tough book
since it covers so much, but it’s definitely worth the time and
money if you’re willing to invest in it.
—A reader
Gaddis is an

extraordinary writer.

Gaddis’ text is working
much better than I expected. The ancillary materials espe-
cially the test bank and Power Point presentations add

greatly to our ability to do some solid, diverse, and effective
teaching.
—George Harrison, Norfolk State University, VA
Could you please tell me when “Starting Out with Java” by
Tony Gaddis will be available for purchase? I am a sopho-
more at Augusta State University, and my school’s first pro-
gramming class uses “Starting out with C++.” I am
transferring to UGA and their first class teaches JAVA. So I
have to teach it to myself. I love your C++ book—it makes
everything so easy to understand, and I know that I can’t go
wrong with the JAVA text.
—Christopher Savage, student
I’ve never seen a beginners C++ book that is as well struc-
tured and reader-friendly as this one. If you are in the mar-
ket for an intro to C++ book, look no further.
—A reader
I have found the Gaddis book to be a wonderful textbook for
our students. It is highly readable, and I am pleased that

most students are actually reading the text

.
—Brenda Boyce, C++ Instructor
Beginners using the Linux operating system and compiling
with gcc will not have a problem with the examples in this
book. I like the fact that the author even explains how to
compile programs under Linux, which helped me out a lot,
being a beginner myself.
—Justin Sinclair, San Francisco, CA
As an instructor in the community-college system, I have stu-

dents with wide-ranging abilities—from remedial to
advanced. Though I haven’t had time to study the whole book
(yet), it has many good features, all of which I can’t list.
The most important to me is how the book proceeds.
Though this book is exhaustive (i.e., covers each of its topics
very thoroughly), it goes step-by-step to teach the basics of the
programming process in an organized fashion. Such a pro-
gressive approach is MUCH better than a “here’s EVERY-
THING on one topic” approach (see any book by the Deitels);
beginning students don’t NEED to know the details. Any pro-
gramming instructor who thinks about how he/she learned
will recognize that he/she learned broad, general basics and
only picked up the details through practice.
…Mr. Gaddis’ book is the BEST I’ve seen in years.
—Reviewer, Wake Technical Community College
Gaddis’ book is a good, solid book and teachers should be
successful using it. Students in our Bachelors program find
the book clear, easy to follow and therefore, they like it very
much.
—An instructor from Touro College, NY
This is an excellent book for those looking to learn the C++
language. It starts off with the absolute basics and goes
through medium-level OOP programming.
—Reviewer from Dallas, TX
My students say Gaddis is the best thing they’ve seen since
sliced bread.
—Tom Gilman, College of the Desert

GaddA2005.book Page ii Friday, September 16, 2005 11:52 AM
Early Objects

5th Edition
Tony Gaddis
Judy Walters
Godfrey Muganda

GaddA2005.book Page iii Friday, September 16, 2005 11:52 AM

Publisher Greg Tobin
Senior Acquisitions Editor Michael Hirsch
Editorial Assistant Lindsey Triebel
Managing Editor Patty Mahtani
Cover Designer Joyce Cosentino Wells
Media Producer Bethany Tidd
Marketing Manager Michelle Brown
Marketing Assistant Dana Lopreato
Senior Manufacturing Buyer Caroline Fell
Text Design, Composition Stephen Adams
Proofreader Kristin Furino
Production Coordination Mario M. Rodriguez
Access the latest information about Addison-Wesley titles from our World Wide Web site:
/>Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trade-
marks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the
designations have been printed in initial caps or all caps.
The programs and applications presented in this book have been included for their instructional value. They have
been tested with care but are not guaranteed for any particular purpose. The publisher does not offer any warran-
ties or representations, nor does it accept any liabilities with respect to the programs or applications.

Library of Congress Cataloging-in-Publication Data

Gaddis, Tony.

Starting out with C++ : early objects / Tony Gaddis, Judy Walters, Godfrey
Muganda 5th ed.
p. cm.
ISBN 0-321-38348-6
1. C++ (Computer program language) I. Walters, Judy. II. Muganda,
Godfrey. III. Title.
QA76.73.C153G33 2005b
005.13'3 dc22 2005022443
Copyright © 2006 Pearson Education, Inc.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior writ-
ten permission of the publisher. Printed in the United States of America. For information on obtaining permis-
sion for use of material in this work, please submit a written request to Pearson Education, Inc., Rights and
Contracts Department, 75 Arlington Street, Suite 300, Boston, MA 02116, fax your request to 617-848-7047, or
e-mail at />ISBN 0-321-38348-6
1 2 3 4 5 6 7 8 9 10—CRW—09 08 07 06 05

GaddA2005.book Page iv Friday, September 16, 2005 11:52 AM

v

Contents at a Glance

CHAPTER 1

Introduction to Computers and Programming

1

CHAPTER 2


Introduction to C++

29

CHAPTER 3

Expressions and Interactivity

79

CHAPTER 4

Making Decisions

167

CHAPTER 5

Looping

255

CHAPTER 6

Functions

313

CHAPTER 7


Introduction to Classes and Objects

391

CHAPTER 8

Arrays

477

CHAPTER 9

Searching and Sorting Arrays

567

CHAPTER 10

Pointers

607

CHAPTER 11

More About Classes and Object-Oriented Programming

657

CHAPTER 12


More About Characters, Strings, and the

string

Class

761

CHAPTER 13

Advanced File and I/O Operations

821

CHAPTER 14

Recursion

889

CHAPTER 15

Polymorphism, Virtual Functions, and Multiple Inheritance

917

CHAPTER 16

Exceptions, Templates, and the Standard Template Library (STL)


957

CHAPTER 17

Linked Lists

1009

CHAPTER 18

Stacks and Queues

1055

CHAPTER 19

Binary Trees

1095

Appendix A The ASCII Character Set

1121

Appendix B Operator Precedence and Associativity

1125
Appendices on the accompanying student CD


Appendix C An Object-Oriented System Development Primer
Appendix D Using UML in Class Design (NEW)
Appendix E Namespaces
Appendix F Passing Command Line Arguments
Appendix G Header File and Library Function Reference
Appendix H Binary Numbers and Bitwise Operations
Appendix I C++ Casts and Run-Time Type Identification
Appendix J Multi-Source File Programs
Appendix K Introduction to Microsoft Visual C++ 6.0



Appendix L Introduction to Borland C++ Builder 5.0
Appendix M Introduction to Microsoft Visual C++ .NET
Appendix N .NET and Managed C++ (NEW)
Appendix O Introduction to Flowcharting
Appendix P Answers to Checkpoints
Appendix Q Answers to Odd-Numbered Review Questions

GaddA2005.book Page v Friday, September 16, 2005 11:52 AM

GaddA2005.book Page vi Friday, September 16, 2005 11:52 AM

vii

Contents

Preface xv

CHAPTER 1


Introduction to Computers and Programming

1
1.1

Why Program?

1
1.2

Computer Systems: Hardware and Software

2
1.3

Programs and Programming Languages

6
1.4

What Is a Program Made of?

12
1.5

Input, Processing, and Output

16
1.6


The Programming Process

18
1.7

Procedural and Object-Oriented Programming

22
1.8

Case Studies

24
1.9

Review Questions and Exercises

25
CHAPTER 2

Introduction to C++

29
2.1

The Parts of a C++ Program

29
2.2


The

cout

Object

33
2.3

The

#include

Directive

37
2.4

Standard and Prestandard C++

39
2.5

Variables, Constants, and the Assignment Statement

40
2.6

Identifiers


45
2.7

Integer Data Types

47
2.8

The

char

Data Type

52
2.9

The C++

string

Class

56
2.10

Floating-Point Data Types

57

2.11

The

bool

Data Type

61
2.12

Determining the Size of a Data Type

62
2.13

More on Variable Assignments and Initialization

63
2.14

Scope

64
2.15

Arithmetic Operators

65
2.16


Comments

68
2.17

Focus on Software Engineering:

Programming Style

70
2.18

Case Studies

72
2.19

Review Questions and Exercises

72
CHAPTER 3

Expressions and Interactivity

79
3.1

The


cin

Object

79
3.2

Mathematical Expressions

85
3.3

Implicit Type Conversion

93

GaddA2005.book Page vii Friday, September 16, 2005 11:52 AM

Contents

viii
3.4

Explicit Type Conversion

95
3.5

Overflow and Underflow


98
3.6

Named Constants

101
3.7

Multiple and Combined Assignment

107
3.8

Formatting Output

111
3.9

Working with Characters and String Objects

121
3.10

Using C-Strings

128
3.11

More Mathematical Library Functions


133
3.12

Introduction to Files

138
3.13

Focus on Object-Oriented Programming:

Member Functions

146
3.14

Focus on Debugging:

Hand Tracing a Program

147
3.15

Green Fields Landscaping Case Study—Part 1

149
3.16

Additional Case Studies

152

3.17

Review Questions and Exercises

152
CHAPTER 4

Making Decisions

167
4.1

Relational Operators

167
4.2

The

if

Statement

173
4.3

The

if/else


Statement

183
4.4

The

if/else



if

Statement

186
4.5

Menus

192
4.6

Nested

if

Statements

194

4.7

Logical Operators

198
4.8

Checking Numeric Ranges with Logical Operators

206
4.9

Validating User Input

207
4.10

More About Variable Definitions and Scope

209
4.11

Comparing Characters and Strings

215
4.12

The Conditional Operator

219

4.13
The
switch
Statement
223
4.14
Enumerated Data Types
232
4.15
Testing for File Open Errors
235
4.16
Focus on Testing and Debugging: Validating Output Results
236
4.17
Green Fields Landscaping Case Study—Part 2
239
4.18
Additional Case Studies
243
4.19
Review Questions and Exercises
243
CHAPTER 5
Looping
255
5.1
The Increment and Decrement Operators
255
5.2

Introduction to Loops: The
while
Loop
260
5.3
Counters
264
5.4
Letting the User Control the Loop
266
5.5
Keeping a Running Total
268
5.6
Sentinels
269
5.7
Using a Loop to Read Data From a File
271
GaddA2005.book Page viii Friday, September 16, 2005 11:52 AM
Contents
ix
5.8
The
do-while
and
for
Loops
274
5.9

Deciding Which Loop to Use
284
5.10
Nested Loops
285
5.11
Breaking Out of a Loop
288
5.12
The
continue
Statement
290
5.13
Focus on Software Engineering: Using Loops for Data Validation
292
5.14
Focus on Testing and Debugging: Creating Good Test Data
295
5.15
Central Mountain Credit Union Case Study
298
5.16
Additional Case Studies
303
5.17
Review Questions and Exercises
303
CHAPTER 6
Functions

313
6.1
Modular Programming
313
6.2
Defining and Calling Functions
314
6.3
Function Prototypes
322
6.4
Sending Data into a Function
324
6.5
Passing Data by Value
328
6.6
The
return
Statement
332
6.7
Returning a Value from a Function
334
6.8
Returning a Boolean Value
338
6.9
Using Functions in a Menu-Driven Program
340

6.10
Local and Global Variables
343
6.11
Static Local Variables
349
6.12
Default Arguments
353
6.13
Using Reference Variables as Parameters
357
6.14
Overloading Functions
365
6.15
The
exit()
Function
369
6.16
Stubs and Drivers
373
6.17
Little Lotto Case Study
376
6.18
Additional Case Studies
381
6.19

Review Questions and Exercises
381
CHAPTER 7
Introduction to Classes and Objects
391
7.1
Combining Data into Structures
391
7.2
Accessing Structure Members
394
7.3
Initializing a Structure
398
7.4
Nested Structures
402
7.5
Structures as Function Arguments
406
7.6
Returning a Structure from a Function
410
7.7
Unions
413
7.8
Abstract Data Types
417
7.9

Object-Oriented Programming
419
7.10
Introduction to Classes
423
7.11
Introduction to Objects
425
GaddA2005.book Page ix Friday, September 16, 2005 11:52 AM
Contents
x
7.12
Defining Member Functions
427
7.13
Focus on Software Engineering: Design Considerations
434
7.14
Using a Constructor with a Class
439
7.15
Overloading Constructors
440
7.16
Destructors
443
7.17
Input Validation Objects
447
7.18

Using Private Member Functions
451
7.19
Home Software Company OOP Case Study
454
7.20
Focus on Software Engineering: Object-Oriented Analysis
461
7.21
Additional Case Studies
464
7.22
Review Questions and Exercises
464
CHAPTER 8
Arrays
477
8.1
Arrays Hold Multiple Values
477
8.2
Accessing Array Elements
479
8.3
Inputting and Displaying Array Contents
481
8.4
Array Initialization
487
8.5

Processing Array Contents
493
8.6
Using Parallel Arrays
502
8.7
The
typedef
Statement
506
8.8
Arrays as Function Arguments
507
8.9
Two-Dimensional Arrays
516
8.10
Arrays with Three or More Dimensions
524
8.11
Vectors
528
8.12
National Commerce Bank Case Study
540
8.13
Arrays of Structures
543
8.14
Arrays of Class Objects

547
8.15
Additional Case Studies
555
8.16
Review Questions and Exercises
556
CHAPTER 9
Searching and Sorting Arrays
567
9.1
Focus on Software Engineering: Introduction to Search Algorithms
567
9.2
Demetris Leadership Center Case Study—Part 1
574
9.3
Focus on Software Engineering: Introduction to Sorting Algorithms
581
9.4
Demetris Leadership Center Case Study—Part 2
589
9.5
Sorting and Searching Vectors
596
9.6
Additional Case Studies
601
9.7
Review Questions and Exercises

602
CHAPTER 10
Pointers
607
10.1
Getting the Address of a Variable
607
10.2
Pointer Variables
609
10.3
The Relationship Between Arrays and Pointers
613
10.4
Pointer Arithmetic
617
10.5
Initializing Pointers
619
GaddA2005.book Page x Friday, September 16, 2005 11:52 AM
Contents
xi
10.6
Comparing Pointers
621
10.7
Pointers as Function Parameters
624
10.8
Focus on Software Engineering: Dynamic Memory Allocation

628
10.9
Focus on Software Engineering: Returning Pointers from Functions
632
10.10
Pointers to Structures and Class Objects
635
10.11
Focus on Software Engineering: Selecting Members of Objects
641
10.12
United Cause Relief Agency Case Study
643
10.13
Additional Case Studies
651
10.14
Review Questions and Exercises
652
CHAPTER 11
More About Classes and Object-Oriented Programming
657
11.1
The
this
Pointer and Constant Member Functions
657
11.2
Static Members
662

11.3
Friends of Classes
669
11.4
Memberwise Assignment
675
11.5
Copy Constructors
677
11.6
Operator Overloading
685
11.7
Type Conversion Operators
721
11.8
Convert Constructors
726
11.9
Object Composition
730
11.10
Inheritance
732
11.11
Protected Members and Class Access
736
11.12
Constructors, Destructors, and Inheritance
742

11.13
Overriding Base Class Functions
747
11.14
Case Studies
750
11.15
Review Questions and Exercises
750
CHAPTER 12
More About Characters, Strings, and the
string
Class
761
12.1
C-strings
761
12.2
Library Functions for Working with C-Strings
766
12.3
String/Numeric Conversion Functions
778
12.4
Character Testing
781
12.5
Character Case Conversion
786
12.6

Writing Your Own C-String Handling Functions
788
12.7
More About the C++
string
Class
794
12.8
Creating Your Own String Class
799
12.9
Advanced Software Enterprises Case Study
811
12.10
Additional Case Studies
813
12.11
Review Questions and Exercises
814
CHAPTER 13
Advanced File and I/O Operations
821
13.1
Files
821
13.2
Output Formatting
830
13.3
Passing File Stream Objects to Functions

838
13.4
More Detailed Error Testing
840
GaddA2005.book Page xi Friday, September 16, 2005 11:52 AM
Contents
xii
13.5
Member Functions for Reading and Writing Files
844
13.6
Working with Multiple Files
854
13.7
Binary Files
855
13.8
Creating Records with Structures
859
13.9
Random-Access Files
863
13.10
Opening a File for Both Input and Output
870
13.11
Online Friendship Connections Case Study: Object Serialization
875
13.12
Additional Case Studies

880
13.13
Review Questions and Exercises
881
CHAPTER 14
Recursion
889
14.1
Introduction to Recursion
889
14.2
The Recursive Factorial Function
897
14.3
The Recursive gcd Function
899
14.4
Solving Recursively Defined Problems
900
14.5
A Recursive Binary Search Function
902
14.6
Focus on Problem Solving and Program Design: The QuickSort Algorithm
904
14.7
Focus on Problem Solving: Exhaustive and Enumeration Algorithms
908
14.8
Focus on Software Engineering: Recursion Versus Iteration

912
14.9
Case Studies
913
14.10
Review Questions and Exercises
913
CHAPTER 15
Polymorphism, Virtual Functions, and Multiple Inheritance
917
15.1
Type Compatibility in Inheritance Hierarchies
917
15.2
Polymorphism and Virtual Member Functions
921
15.3
Abstract Base Classes and Pure Virtual Functions
926
15.4
Multiple and Virtual Inheritance
931
15.5
Focus on Object-Oriented Programming: Composition Versus Inheritance
940
15.6
Secure Encryption Systems, Inc. Case Study
945
15.7
Review Questions and Exercises

949
CHAPTER 16
Exceptions, Templates, and the Standard Template Library (STL)
957
16.1
Exceptions
957
16.2
Function Templates
969
16.3
Class Templates
978
16.4
Class Templates and Inheritance
984
16.5
Introduction to the Standard Template Library
988
16.6
Case Studies
1003
16.7
Review Questions and Exercises
1003
CHAPTER 17
Linked Lists
1009
17.1
Introduction to the Linked List ADT

1009
17.2
Linked List Operations
1016
17.3
A Linked List Template
1032
17.4
Recursive Linked List Operations
1037
GaddA2005.book Page xii Friday, September 16, 2005 11:52 AM
Contents
xiii
17.5
Variations of the Linked List
1043
17.6
The STL
list
Container
1044
17.7
Reliable Software Systems, Inc. Case Study
1046
17.8
Additional Case Studies
1049
17.9
Review Questions and Exercises
1050

CHAPTER 18
Stacks and Queues
1055
18.1
Introduction to the Stack ADT
1055
18.2
Dynamic Stacks
1065
18.3
The STL
stack
Container
1069
18.4
Introduction to the Queue ADT
1071
18.5
Dynamic Queues
1079
18.6
The STL
deque
and
queue
Containers
1082
18.7
Focus on Problem Solving and Program Design: Eliminating Recursion
1085

18.8
Review Questions and Exercises
1090
CHAPTER 19
Binary Trees
1095
19.1
Definition and Applications of Binary Trees
1095
19.2
Binary Search Tree Operations
1099
19.3
Template Considerations for Binary Search Trees
1116
19.4
Case Studies
1116
19.5
Review Questions and Exercises
1116
Appendix A The ASCII Character Set 1121
Appendix B Operator Precedence and Associativity 1125
Index 1127
GaddA2005.book Page xiii Friday, September 16, 2005 11:52 AM
GaddA2005.book Page xiv Friday, September 16, 2005 11:52 AM
xv
Preface
Welcome to Starting Out with C++: Early Objects, 5th edition. In previous editions this book was
called Alternate Version of Starting Out With C++. This book is intended for use in a two-

semester C++ programming sequence, or an accelerated one-semester course. Students new to
programming, as well those with prior course work in other languages, will find this text benefi-
cial. The fundamentals of programming are covered for the novice, while the details, pitfalls, and
nuances of the C++ language are explored in-depth for both the beginner and more experienced
student. The book is written with clear, easy-to-understand language and it covers all the neces-
sary topics for an introductory programming course. This text is rich in example programs that
are concise, practical, and real world oriented, ensuring that the student not only learns how to
implement the features and constructs of C++, but why and when to use them.
What’s New in the Fifth Edition
 Several Programming Challenges in each chapter have been selected for inclusion in
Addison-Wesley’s MyCodeMate. MyCodeMate allows students to complete the Program-
ming Challenges on-line, with automated assistance and feedback provided as needed. It
also provides instructors with information on student progress and helps with course
management.
 The
double
data type, rather than the
float
data type, has become the standard used
throughout the book for floating-point variables.
 The standard has been adopted throughout the book of giving named constants identi-
fier names consisting entirely of uppercase characters and underscores. For example:
const double INTEREST_RATE = .03;
 Array size declarators, previously specified with literals, are now specified with named
constants. For example:
const int SIZE = 20;
double sample[SIZE];
GaddA2005.book Page xv Friday, September 16, 2005 11:52 AM
Preface
xvi

 The appendices have been reorganized and each appendix is now stored in its own PDF
file, with numbering starting from page 1. This will make it easier for students to locate
appendix information.
 Two new appendices have been added:
– Using UML in Class Design
– .NET and Managed C++
 A UML icon has been added throughout the text where appropriate to refer students to
the contents of the new appendix.
 New and improved Programming Challenges have been added throughout the book.
Beginning with Chapter 7, additional problems that use classes have been added.
 Each Programming Challenge integrated into MyCodeMate is followed in the text by a
“twin” problem that has the student either build on the original program or create a new
program that is similar in design to it.
Organization of the Text
This text teaches C++ in a step-by-step fashion. Each chapter covers a major set of topics and
builds knowledge as the student progresses through the book. Although the chapters can be
easily taught in their existing sequence, flexibility is provided. The following dependency dia-
gram (Figure P-1) suggests possible sequences of instruction.
Chapter 1 covers fundamental hardware, software, and programming concepts. The
instructor may choose to skip this chapter if the class has already mastered those topics. Chap-
ters 2 through 6 cover basic C++ syntax, data types, expressions, selection structures, repetition
structures, and functions. Each of these chapters builds on the previous chapter and should be
covered in the order presented.
Chapter 7 introduces object-oriented programming and includes structures and classes. It
can be covered any time after Chapter 6, but before Chapter 11. Instructors who prefer to intro-
duce arrays before classes can do so by covering Chapter 8 before Chapter 7. In this case it will
only be necessary to postpone sections 8.13 and 8.14 until Chapter 7 has been covered.
As the diagram (Figure P-1) illustrates, in the second half of the book Chapters 11, 12, 13,
and 14 can be covered in any order. Chapters 11, 15, and 16, however, should be done in
sequence. Instructors who wish to introduce data structures at an earlier point in the course,

without having first covered advanced C++ and OOP features, can do so by covering Chapter
17 (Linked Lists), followed by Chapters 18 and 19 (Stacks & Queues and Binary Trees), any
time after Chapter 14 (Recursion). In this case it is necessary to simply omit the sections in
Chapters 17–19 that deal with templates and the Standard Template Library.
GaddA2005.book Page xvi Friday, September 16, 2005 11:52 AM
Preface
xvii
Figure P-1
Chapter 1
Introduction
Chapters 2–6
Basic
Language
Elements
Chapter 10
Pointers
Chapter 7
OOP Introduction
Chapter 8
Arrays
Chapter 11
More OOP
Chapter 12
Advanced
Strings
Chapter 13
Advanced Files
and I/O
Chapter 14
Recursion

Chapter 17
Linked Lists
Chapter 15
Adv. OOP
Chapter 16
Exceptions
Templates
and STL
Chapter 18
Stacks and
Queues
Chapter 19
Binary Trees
Chapter 9
Searching
and Sorting
GaddA2005.book Page xvii Friday, September 16, 2005 11:52 AM
Preface
xviii
Brief Overview of Each Chapter
Chapter 1: Introduction to Computers and Programming
This chapter provides an introduction to the field of computer science and covers the funda-
mentals of hardware, software, operating systems, programming, problem solving, and soft-
ware engineering. The components of programs, such as key words, variables, operators, and
punctuation are covered. The tools of the trade, such as hierarchy charts and pseudocode are
also presented.
Chapter 2: Introduction to C++
This chapter gets the student started in C++ by introducing the basic parts of a C++ program,
data types, variable definitions, assignment statements, constants, comments, program output,
and simple arithmetic operations. The C++ string class is presented and string objects are used

from this point on in the book as the primary method of handling strings. Programming style
conventions are introduced and good programming style is modeled here, as it is throughout
the text. An optional section explains the difference between ANSI standard and prestandard
C++ programs.
Chapter 3: Expressions and Interactivity
In this chapter the student learns to write programs that input and handle numeric, character,
and string data. The use of arithmetic operators and the creation of mathematical expressions
are covered, with emphasis on operator precedence. Debugging is introduced, with a section on
hand tracing a program. Sections are also included on using sequential files, on simple output
formatting, on data type conversion and type casting, and on using library functions that work
with numbers. For those who wish to cover them, there is also a section on C-strings.
Chapter 4: Making Decisions
Here the student learns about relational expressions and how to control the flow of a program
with the
if
,
if/else
, and
if/else

if
statements. Logical operators, the conditional operator,
and the
switch
statement are also covered. Applications of these constructs, such as menu-
driven programs, are illustrated. This chapter also continues the theme of debugging with a
section on validating output results.
Chapter 5: Looping
This chapter covers C++’s repetitive control mechanisms. The
while

loop,
do-while
loop, and
for
loop are taught, along with a variety of methods to control them. These include using
counters, user input, end sentinels, and end-of-file signals. Applications utilizing loops, such as
data validation, are covered. The emphasis on testing and debugging continues, with a section
on creating good test data.
GaddA2005.book Page xviii Friday, September 16, 2005 11:52 AM
Preface
xix
Chapter 6: Functions
In this chapter the student learns how and why to modularize programs, using both
void
and
value returning functions. Parameter passing is covered, with emphasis on when arguments
should be passed by value versus when they need to be passed by reference. Scope of variables is
covered and sections are provided on local versus global variables and on static local variables.
Overloaded functions are also introduced and demonstrated.
Chapter 7: Introduction to Classes and Objects
In this chapter the text begins to focus on the object-oriented paradigm. There is a general
introduction to object-oriented analysis and to object-oriented programming, as well as spe-
cific material provided on how to group and encapsulate data using both structures and classes.
Member variables and member functions are introduced and the student learns how to write
and call member functions. Information is also provided on which member variables and func-
tions should be public and which should be private.
Chapter 8: Arrays
In this chapter the student learns to create and work with single and multidimensional arrays.
Many examples of array processing are provided including examples illustrating how to find
the sum, average, highest and lowest values in an array and how to sum the rows, columns, and

all elements of a two-dimensional array. Programming techniques using parallel arrays are also
demonstrated and the student is shown how to use a data file as an input source to populate an
array. STL vectors are introduced and compared to arrays. Sections on arrays of structures and
arrays of class objects have been placed at the end of the chapter, so they can be covered now or
saved for later if the instructor wishes to cover this chapter before Chapter 7.
Chapter 9: Searching and Sorting Arrays
Here the student learns the basics of searching for information stored in arrays and of sorting
arrays. The chapter covers the Linear Search, Binary Search, Bubble Sort, and Selection Sort
algorithms. In addition there is a section on sorting and searching STL vectors.
Chapter 10: Pointers
This chapter explains how to use pointers. The topics include pointer arithmetic, initialization
of pointers, comparison of pointers, pointers and arrays, pointers and functions, dynamic
memory allocation, and more.
Chapter 11: More About Classes and Object-Oriented Programming
This chapter continues the study of classes and object-oriented programming. It covers object
composition and inheritance as well as constant member functions, static members, friends,
memberwise assignment, copy constructors, operator overloading, object type conversion
operators, and convert constructors.
GaddA2005.book Page xix Friday, September 16, 2005 11:52 AM
Preface
xx
Chapter 12: More about Characters, Strings, and the
string
Class
This chapter covers standard library functions for working with characters and C-strings and
includes a review of the internal storage of C-strings. Topics such as passing C-strings to func-
tions, and conversion between numeric and string forms are covered. Additional material
about the C++ string class and its member functions and operators is also presented.
Chapter 13: Advanced File and I/O Operations
This chapter covers sequential access, random access, text, and binary files. The various modes

for opening files are discussed, as well as the many methods for reading and writing file con-
tents. Advanced output formatting is also covered.
Chapter 14: Recursion
In this chapter recursion is defined and demonstrated. A visual trace of recursive calls is pro-
vided and recursive applications are discussed. Many recursive algorithms are presented,
including recursive functions for finding factorials, finding a greatest common denominator
(GCD), performing a binary search, and sorting (QuickSort). For students who need more
challenge, there is a section on exhaustive and enumeration algorithms.
Chapter 15: Polymorphism, Virtual Functions, and
Multiple Inheritance
The study of classes and object-oriented programming continues in this chapter with the intro-
duction of more advanced concepts such as polymorphism and virtual functions. Information
is also presented on abstract base classes, pure virtual functions, type compatibility within an
inheritance hierarchy, multiple inheritance, and virtual inheritance. The difference between is-
a and has-a relations is discussed and information is presented on when to use inheritance ver-
sus when to use composition.
Chapter 16: Exceptions, Templates, and the Standard Template
Library (STL)
Here the student learns to develop enhanced error trapping techniques using exceptions. Dis-
cussion then turns to function and class templates as a method for writing generic code. Finally,
the student is introduced to the containers, iterators, and algorithms offered by the Standard
Template Library (STL).
Chapter 17: Linked Lists
This chapter introduces concepts and techniques needed to work with lists. A linked list ADT is
developed and the student is taught to code operations such as creating a linked list, appending
a node, traversing the list, searching for a node, inserting a node, deleting a node, and destroy-
ing a list. A linked list class template is also demonstrated.
Chapter 18: Stacks and Queues
In this chapter the student learns to create and use static and dynamic stacks and queues. The
operations of stacks and queues are defined, and templates for each ADT are demonstrated.

GaddA2005.book Page xx Friday, September 16, 2005 11:52 AM
Preface
xxi
Chapter 19: Binary Trees
This chapter covers the binary tree ADT and demonstrates many binary tree operations. The
student learns to traverse a tree, insert an element, delete an element, replace an element, test
for an element, and destroy a tree.
Appendices
Appendix A: The ASCII Character Set A list of the ASCII and extended ASCII characters
and their codes.
Appendix B: Operator Precedence and Associativity A list of the C++ operators with
their precedence and associativity.
The following appendices are on the accompanying student CD
Appendix C: An Object-Oriented System Development Primer A short introduc-
tion to object-oriented analysis and design.
Appendix D: Using UML in Class Design (NEW) A brief introduction to the Unified
Modeling Language (UML) with examples of its use.
Appendix E: Namespaces An explanation of namespaces and their purpose, with exam-
ples provided on how to define a namespace and access its members.
Appendix F: Passing Command Line Arguments An introduction to writing C++
programs that accept command line arguments. This appendix will be useful to students work-
ing in a command line environment, such as UNIX or Linux.
Appendix G: Header File and Library Function Reference A reference for the C++
library functions and header files used in the book.
Appendix H: Binary Numbers and Bitwise Operations A guide to the binary number
system and the C++ bitwise operators, as well as a tutorial on the internal storage of integers.
Appendix I: C++ Casts and Run-Time Type Identification An introduction to the
different ways of doing type casting in C++, and to run-time type identification.
Appendix J: Multi-Source File Programs A tutorial on how to create, compile, and link
programs with multiple source files. Includes the use of function header files, class specification

files, and class implementation files.
Appendix K: Introduction to Microsoft Visual C++ 6.0 A tutorial on how to start a
project using Microsoft Visual C++, compile and run a program, save source files, and more.
The Visual C++ 6.0
getline()
bug is documented and a solution provided.
Appendix L: Introduction to Borland C++ Builder 5.0 A tutorial on how to start a
Borland C++ Builder project, compile and run a program, save source files, and more.
Appendix M: Introduction to Microsoft Visual C++ .NET A tutorial on how to start a
project using Microsoft Visual C++ .NET, compile and run a program, save source files, and more.
Appendix N: .NET and Managed C++ (NEW) A short introduction to Microsoft .NET
and managed C++.
GaddA2005.book Page xxi Friday, September 16, 2005 11:52 AM
Preface
xxii
Appendix O: Introduction to Flowcharting A tutorial which introduces flowcharting
and its symbols. Includes handling sequence, selection, case, repetition, and calls to other mod-
ules. Sample flowcharts for several of the book’s example programs are presented.
Appendix P: Answers to Checkpoints A tool students can use to assess their under-
standing by comparing their answers to the Checkpoint exercises against this appendix. The
answers to all Checkpoint exercises are included.
Appendix Q: Answers to Odd-Numbered Review Questions Another tool students
can use to gauge their understanding and progress.
Features of the Text
Concept Statements Each major section of the text starts with a concept statement. This
statement summarizes the ideas of the section.
Example Programs The text has over 350 complete example programs, each designed to
highlight the topic currently being studied. In most cases, these are
practical, real-world examples. Source code for these programs is
provided so that students can run the programs themselves.

Program Output After each example program there is a sample of its screen output. This
immediately shows the student how the program should function.
Checkpoints Checkpoints are questions placed throughout each chapter as a self-test
study aid. Answers for all Checkpoint questions are provided on the stu-
dent CD so students can check how well they have learned a new topic.
Notes Notes appear at appropriate places throughout the text. They are
short explanations of interesting or often misunderstood points rel-
evant to the topic at hand.
Warnings Warnings are notes that caution the student about certain C++
features, programming techniques, or practices that can lead to
malfunctioning programs or lost data.
Case Studies Case studies that simulate real-world applications appear in many
chapters throughout the text, with complete code provided for each
one on the student CD. These case studies are designed to highlight
the major topics of the chapter in which they appear.
Review Questions Each chapter presents a thorough and diverse set of review questions,
and Exercises such as fill-in-the-blank and short answer, that check the student’s mas-
tery of the basic material presented in the chapter. These are followed
by exercises requiring problem solving and analysis, such as the
Algorithm Workbench, Predict the Output, and Find the Errors sections.
Each chapter ends with a Soft Skills exercise which focuses on commu-
nication and group process skills. Answers to the odd numbered review
questions and review exercises are provided on the student CD.
GaddA2005.book Page xxii Friday, September 16, 2005 11:52 AM
Preface
xxiii
Programming Challenges Each chapter offers a pool of programming exercises designed to
solidify the student’s knowledge of the topics currently being stud-
ied. In most cases the assignments present real-world problems to
be solved. When applicable, these exercises include input valida-

tion rules.
Group Projects There are several group programming projects throughout the text,
intended to be constructed by a team of students. One student
might build the program’s user interface, while another student
writes the mathematical code, and another designs and implements
a class the program uses. This process is similar to the way many
professional programs are written and encourages team work
within the classroom.
Software Development Project:
Serendipity Booksellers This is an on-going project that instructors can optionally assign to
teams of students. It systematically develops a “real world” software
package: a point-of-sale program for the fictitious Serendipity
Booksellers organization. The Serendipity assignment for each
chapter adds more functionality to the software, using constructs
and techniques covered in that chapter. When complete, the pro-
gram will act as a cash register, manage an inventory database, and
produce a variety of reports.
Supplements
Student CD
This CD includes:
 Answers to all Checkpoint questions (Appendix P)
 Answers to all odd-numbered Review Questions and Exercises (Appendix Q)
 Complete source code for every program included in the book
 Additional case studies, complete with source code
 A full set of appendices (including several tutorials) that accompany the book
 Borland C++ Builder 6.0, Personal Edition
If a CD did not come with your book or you can’t locate your CD, you can access most of these
items at />Other CDs Upon Request (contact your campus Addison-Wesley representative for the
specific ISBN to order)
 Microsoft Visual C++ 6.0

 Microsoft Visual C++ .NET
 CodeWarrior
GaddA2005.book Page xxiii Friday, September 16, 2005 11:52 AM
Preface
xxiv
MyCodeMate—Your Own T.A. Just a Click Away
Addison-Wesley’s MyCodeMate is a book-specific Web resource that provides tutorial help and
evaluation of student programs. Example programs throughout the book and selected Pro-
gramming Challenges from every chapter have been integrated into MyCodeMate. Using this
tool, a student is able to write and compile programs from any computer with Internet access,
and receive guidance and feedback on how to proceed and on how to address compiler error
messages. Instructors can track each student’s progress on Programming Challenges from the
text or can develop projects of their own. A complimentary subscription to MyCodeMate is
offered when the access code is ordered in a package with a new copy of this text. Subscrip-
tions can also be purchased online. For more information visit www.mycodemate.com, or con-
tact your campus Addison-Wesley representative.
Instructor Resources
The following supplements are available to qualified instructors only. Visit the Addison-Wesley
Instructor Resource Center (www.aw.com/irc) or send an email to for
information on how to access them:
 Answers to all Review Questions in the text
 Solutions for all Programming Challenges in the text
 PowerPoint presentation slides for every chapter
 Computerized test bank
 Answers to all Student Lab Manual questions
 Solutions for all Student Lab Manual programs
Additional Supplements
The following supplementary material is also available for this textbook. Contact your campus
Addison-Wesley representative for more information.
 Lab Manual to Accompany Starting Out with C++: Early Objects, 5th Edition,

co-authored by Judy Walters, Dean Defino, and Michael Bardzell
Textbook Web site
A Web site for the Starting Out With C++ series of books is located at the following URL:
/> GaddA2005.book Page xxiv Friday, September 16, 2005 11:52 AM
Preface
xxv
Which Gaddis C++ book is right for you?
The Starting Out with C++ Series includes three books, one of which is sure to fit your course:
 Starting Out with C++: Control Structures through Objects (formerly called the “Standard
Version”);
 Starting Out With C++: Early Objects (formerly called the “Alternate Version”);
 Starting Out with C++: Brief Version.
The following chart will help you determine which book is right for your course.

From Control Structures through Objects

Brief Version

Early Objects
LATE INTRODUCTION OF OBJECTS
Classes are introduced in Chapter 13 of the
standard text and Chapter 11 of the brief text,
after control structures, functions, arrays, and
pointers. Advanced OOP topics, such as
inheritance and polymorphism, are covered in
the following two chapters.
EARLIER INTRODUCTION OF OBJECTS
Classes are introduced in Chapter 7, after control
structures and functions, but before arrays and
pointers. Their use is then integrated into the

remainder of the text. Advanced OOP topics,
such as inheritance and polymorphism, are
covered in Chapters 11 and 15.
USE OF C-STRINGS
Null-terminated C-strings are used throughout,
with the C++ string class covered briefly.
USE OF STRING OBJECTS
Standard library string class objects are used
throughout, with C-strings covered briefly.
INTRODUCTION OF DATA STRUCTURES AND
RECURSION
Linked lists, stacks and queues, and binary trees
are introduced in the final chapters of the
standard text. Recursion is covered after stacks
and queues, but before binary trees. These
topics are not covered in the brief text, though
it does have appendices dealing with linked
lists and recursion.
INTRODUCTION OF DATA STRUCTURES AND
RECURSION
Linked lists, stacks and queues, and binary trees
are introduced in the final chapters of the text,
after the chapter on recursion.
GaddA2005.book Page xxv Friday, September 16, 2005 11:52 AM

×