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

Tony gaddis starting out with c++ from controll structures througt 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 (4.98 MB, 987 trang )

C++ Quick Reference
C++ Data Ty pe s
D
Data Type Description
char Character
unsigned char Unsigned Character
int Integer
short int Short integer
short Same as short int
unsigned short int Unsigned short integer
unsigned short Same as unsigned short int
unsigned int Unsigned integer
unsigned Same as unsigned int
long int Long integer
long Same as long int
unsigned long int Unsigned long integer
unsigned long Same as unsigned long int
float Single precision floating point
double double precision floating point
long double Long double precision floating
point
Commo n l y Used Operators
A
Assign ment Opera tor s
=Assignment
+= Combined addition/assignment
-= Combined subtra ction/assignment
*= Combined multip lication/assignment
/= Combined division/assignment
%= Combined modulus/assignment


A
Arith metic Operator s
+ Addition
- S ubtraction
* Multiplication
/ Division
% Modulus (remainder)
R
Rela t i o nal Operators
< Less than
<= Less than or equal to
> Gre ater than
>= Gre ater than or equal to
== Equal to
!= Not equal to
L
Logical Operator s
&& AND
|| OR
! NOT
I
Increment / Decreme n t
++ Incr ement
Dec rement
For ms of the
if S
Statement
Simp le
i
if Exa m p le

if (
expression
) if(x<y)
statement
; x++;
i
if/e l se Exa m p le
if (
expression
) if(x<y)
statement
; x++;
else else
statement
; x ;
i
if/e l se if Exa m p le
if (
expression
) if(x<y)
statement
; x++;
else if (
expression
) else if (x < z)
statement
; x ;
else else
statement
; y++;

T
To con d i t i o na l ly
-
-execute more than one
s
state ment, enclose t he state me n t s in braces:
Form
E
Exa m p le
if (
expression
) if(x<y)
{{
statement
; x++;
statement
; cout << x;
}}
Condit i o na l Operator ?:
F
Form:
expression
?
expression
:
expression
E
Exa m p le:
x=a<b?a:b;
T

T he s tatement ab o ve wor ks
li ke:
if (a < b)
x=a;
else
x=b;
The
while L
Loop
Form:
E
Exa m p le:
while (
expression
) while (x < 100)
statement
; cout << x++ << endl;
while (
expression
) while (x < 100)
{{
statement
; cout << x << endl;
statement
; x++;
}}
Web Sites
For the
Starting Out with C ++
Series

aw.com/gaddisbooks
For Addison-Wesley Computing
aw.com/computing
The do
-
-
while L
Loop
Form:
E
Exa m p le:
do do
statement
; cout << x++ << endl;
while (
expression
); while (x < 100);
do do
{{
statement
; cout << x << endl;
statement
; x++;
} while (
expression
); } while (x < 100);
LOCATION OF VIDEONOTES IN THE TEXT
Chapter 1 Introduction to Flowcharting, p. 19
Designing a Program with Pseudocode, p. 19
Designing the Account Balance Program, p. 25

Predicting the Result of Problem 33, p. 25
Chapter 2 Using
cout, p. 31
Variable Definitions, p. 37
Assignment Statements and Simple Math Expressions, p. 59
Solving the Restaurant Bill problem, p. 75
Chapter 3 Reading Input with
cin
, p. 79
Formatting Numbers with
setprecision
, p. 115
Writing Data to a File, p. 140
Reading Data from a File, p. 141
Solving the Stadium Seating Problem, p. 152
Chapter 4 The
if
Statement, p. 164
The
if/else
Statement, p. 177
The
if/else

if
Statement, p. 187
Solving the Time Calculator Problem, p. 235
Chapter 5 The
while
Loop, p. 246

The
for
Loop, p. 262
Solving the Calories Burned Problem, p. 291
Chapter 6 Functions and Arguments, p. 309
Value-Returning Functions, p. 322
Solving the Markup Problem, p. 365
Chapter 7 Accessing Array Elements with a Loop, p. 378
Passing an Array to a Function, p. 401
Solving the Chips and Salsa Problem, p. 443
Chapter 8 The Binary Search, p. 454
The Selection Sort, p. 469
Solving the Charge Account Validation Modification Problem, p. 487
Chapter 9 Dynamically Allocating an Array, p. 519
Solving the
getString
Function Problem, p. 538
Chapter 10 Writing a C-String-Handling Function, p. 564
Using the
string
Class, p. 570
Solving the Backward String Problem, p. 584
(continued on next page)
(continued)
LOCATION OF VIDEONOTES IN THE TEXT
Chapter 11 Creating a Structure, p. 591
Passing a Structure to a Function, p. 610
Solving the Weather Statistics Problem, p. 644
Chapter 12 Passing File Stream Objects to Functions, p. 661
Working with Multiple Files, p. 673

Solving the File Encryption Filter Problem, p. 703
Chapter 13 Writing a Class, p. 712
Defining an Instance of a Class, p. 717
Solving the
Employee
Class Problem, p. 792
Chapter 14 Operator Overloading, p. 819
Class Aggregation, p. 848
Solving the
NumDays
Problem, p. 864
Chapter 15 Redefining a Base Class Function in a Derived Class, p. 893
Polymorphism, p. 903
Solving the
Employee
and
ProductionWorker
Classes Problem, p. 936
From Control Structures
through Objects
6th Edition Brief Version
Tony Gaddis
Editor-in-Chief: Michael Hirsch
Editorial Assistant: Stephanie Sellinger
Managing Editor: Jeffrey Holcomb
Senior Production Supervisor: Marilyn Lloyd
Marketing Manager: Erin Davis
Marketing Coordinator: Kathryn Ferranti
Senior Media Buyer: Ginny Michaud
Media Assistant: Katelyn Boller

Senior Manufacturing Buyer: Carol Melville
Project Coordination: Sherrill Redd/Aptara, Inc.
Production Services: Aptara®, Inc.
Art Director, Cover: Linda Knowles
Cover Designer: Joyce Cosentino Wells/JWells Design
Cover Image: Getty Images/Photographer: David Muir
Access the latest information about Addison-Wesley Computer Science 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
warranty or representation, nor does it accept any liabilities with respect to the programs or applications.
The interior of this book was composed in Aptara, Inc. The basal text font is set in Sabon 10/12.5; the chapter
titles, headings, running heads, and folios are all set in Stone Sans; the programming code is set in Courier10
Pitch BT 9/11.
Library of Congress Cataloging-in-Publication Data
Copyright © 2010 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 written per-
mission of the publisher. Printed in the United States of America.
For information on obtaining permission for use of material in this work, please submit a written request to
Pearson Education, Inc., Rights and Contracts Department, 501 Boylston Street, Suite 900, Boston, MA 02116,
fax your request to 617-671-3447, or e-mail at />ISBN 13: 978-0-136-02253-4
ISBN 10: 0-136-02253-7
1 2 3 4 5 6 7 8 9 10—EB—12 11 10 09
v
Contents at a Glance
Preface xiii
CHAPTER 1 Introduction to Computers and Programming 1

CHAPTER 2 Introduction to C++ 27
CHAPTER 3 Expressions and Interactivity 79
CHAPTER 4 Making Decisions 159
CHAPTER 5 Looping 241
CHAPTER 6 Functions 297
CHAPTER 7 Arrays 373
CHAPTER 8 Searching and Sorting Arrays 451
CHAPTER 9 Pointers 491
CHAPTER 10 Characters, Strings, and the string Class 541
CHAPTER 11 Structured Data 589
CHAPTER 12 Advanced File Operations 651
CHAPTER 13 Introduction to Classes 705
CHAPTER 14 More About Classes 801
CHAPTER 15 Inheritance, Polymorphism, and Virtual Functions 871
Appendix A: The ASCII Character Set 945
Appendix B: Operator Precedence and Associativity 949
Index 951
Student CD The following appendices are on the accompanying Student CD.
Appendix C: Introduction to Flowcharting
Appendix D: Using UML in Class Design
Appendix E: Namespaces
Appendix F: Writing Managed C++ Code for the .NET Framework
Appendix G: Passing Command Line Arguments
Appendix H: Header File and Library Function Reference
vi Contents at a Glance
Appendix I: Binary Numbers and Bitwise Operations
Appendix J: Multi-Source File Programs
Appendix K: Stream Member Functions for Formatting
Appendix L: Introduction to Microsoft Visual C++ 2008 Express Edition
Appendix M: Answers to Checkpoints

Appendix N: Answers to Odd Numbered Review Questions
vii
Contents
Table of Location of videonotes
Preface xiii
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 17
1.7 Procedural and Object-Oriented Programming 21
CHAPTER 2 Introduction to C++ 27
2.1 The Parts of a C++ Program 27
2.2 The cout Object 31
2.3 The #include Directive 36
2.4 Variables and Literals 37
2.5 Identifiers 41
2.6 Integer Data Types 42
2.7 The char Data Type 47
2.8 Floating-Point Data Types 52
2.9 The bool Data Type 55
2.10 Determining the Size of a Data Type 56
2.11 Variable Assignments and Initialization 57
2.12 Scope 58
2.13 Arithmetic Operators 59
2.14 Comments 65
2.15 Focus on Software Engineering: Programming Style 67
2.16 If You Plan to Continue in Computer Science: Standard and Prestandard C++ 69

CHAPTER 3 Expressions and Interactivity 79
3.1 The cin Object 79
3.2 Mathematical Expressions 87
3.3 When You Mix Apples and Oranges: Type Conversion 96
viii Contents
3.4 Overflow and Underflow 98
3.5 Type Casting 100
3.6 Named Constants 103
3.7 Multiple Assignment and Combined Assignment 108
3.8 Formatting Output 112
3.9 Formatted Input 121
3.10 Focus on Object-Oriented Programming: More About Member Functions 126
3.11 More Mathematical Library Functions 127
3.12 Focus on Debugging: Hand Tracing a Program 131
3.13 Focus on Problem Solving: A Case Study 133
3.14 Introduction to File Input and Output 136
CHAPTER 4 Making Decisions 159
4.1 Relational Operators 159
4.2 The if Statement 164
4.3 Flags 172
4.4 Expanding the if Statement 173
4.5 The if/else Statement 177
4.6 Nested if Statements 180
4.7 The if/else if Statement 187
4.8 Menus 191
4.9 Logical Operators 195
4.10 Checking Numeric Ranges with Logical Operators 202
4.11 Focus on Software Engineering: Validating User Input 203
4.12 More About Variable Definitions and Scope 205
4.13 Comparing Strings 209

4.14 The Conditional Operator 214
4.15 The switch Statement 218
4.16 Testing for File Open Errors 227
CHAPTER 5 Looping 241
5.1 The Increment and Decrement Operators 241
5.2 Introduction to Loops: The while Loop 246
5.3 Using the while Loop for Input Validation 253
5.4 Counters 255
5.5 The do-while Loop 257
5.6 The for Loop 262
5.7 Keeping a Running Total 272
5.8 Sentinels 275
5.9 Using a Loop to Read Data from a File 276
5.10 Focus on Software Engineering: Deciding Which Loop to Use 279
5.11 Nested Loops 279
5.12 Breaking Out of a Loop 282
5.13 The continue Statement 284
CHAPTER 6 Functions 297
6.1 Focus on Software Engineering: Modular Programming 297
6.2 Defining and Calling Functions 299
6.3 Function Prototypes 307
Contents ix
6.4 Sending Data into a Function 309
6.5 Passing Data by Value 314
6.6 Focus on Software Engineering: Using Functions in a Menu-Driven Program 316
6.7 The return Statement 320
6.8 Returning a Value from a Function 322
6.9 Returning a Boolean Value 330
6.10 Local and Global Variables 332
6.11 Static Local Variables 340

6.12 Default Arguments 343
6.13 Using Reference Variables as Parameters 346
6.14 Overloading Functions 352
6.15 The exit() Function 356
6.16 Stubs and Drivers 359
CHAPTER 7 Arrays 373
7.1 Arrays Hold Multiple Values 373
7.2 Accessing Array Elements 375
7.3 No Bounds Checking in C++ 382
7.4 Array Initialization 385
7.5 Processing Array Contents 390
7.6 Focus on Software Engineering: Using Parallel Arrays 398
7.7 Arrays as Function Arguments 401
7.8 Two-Dimensional Arrays 412
7.9 Arrays of Strings 419
7.10 Arrays with Three or More Dimensions 421
7.11 Focus on Problem Solving and Program Design: A Case Study 423
7.12 If You Plan to Continue in Computer Science: Introduction to the
STL vector 425
CHAPTER 8 Searching and Sorting Arrays 451
8.1 Focus on Software Engineering: Introduction to Search Algorithms 451
8.2 Focus on Problem Solving and Program Design:
A Case Study 458
8.3 Focus on Software Engineering: Introduction to Sorting Algorithms 464
8.4 Focus on Problem Solving and Program Design: A Case Study 472
8.5 If You Plan to Continue in Computer Science: Sorting and
Searching vectors 480
CHAPTER 9 Pointers 491
9.1 Getting the Address of a Variable 491
9.2 Pointer Variables 493

9.3 The Relationship Between Arrays and Pointers 500
9.4 Pointer Arithmetic 504
9.5 Initializing Pointers 506
9.6 Comparing Pointers 507
9.7 Pointers as Function Parameters 509
9.8 Focus on Software Engineering: Dynamic Memory Allocation 518
9.9 Focus on Software Engineering: Returning Pointers from Functions 522
9.10 Focus on Problem Solving and Program Design: A Case Study 529
x Contents
CHAPTER 10 Characters, Strings, and the string Class 541
10.1 Character Testing 541
10.2 Character Case Conversion 545
10.3 Review of the Internal Storage of C-Strings 548
10.4 Library Functions for Working with C-Strings 551
10.5 String/Numeric Conversion Functions 559
10.6 Focus on Software Engineering: Writing Your Own
C-String-Handling Functions 564
10.7 The C++ string Class 570
10.8 Focus on Problem Solving and Program Design: A Case Study 580
CHAPTER 11 Structured Data 589
11.1 Abstract Data Types 589
11.2 Focus on Software Engineering: Combining Data
into Structures 591
11.3 Accessing Structure Members 594
11.4 Initializing a Structure 599
11.5 Arrays of Structures 603
11.6 Focus on Software Engineering: Nested Structures 606
11.7 Structures as Function Arguments 610
11.8 Returning a Structure from a Function 613
11.9 Pointers to Structures 616

11.10 Focus on Software Engineering: When to Use ., When to Use ->,
and When to Use * 619
11.11 Unions 621
11.12 Enumerated Data Types 625
CHAPTER 12 Advanced File Operations 651
12.1 File Operations 651
12.2 File Output Formatting 658
12.3 Passing File Stream Objects to Functions 661
12.4 More Detailed Error Testing 663
12.5 Member Functions for Reading and Writing Files 666
12.6 Focus on Software Engineering: Working with Multiple Files 673
12.7 Binary Files 674
12.8 Creating Records with Structures 680
12.9 Random-Access Files 684
12.10 Opening a File for Both Input and Output 692
CHAPTER 13 Introduction to Classes 705
13.1 Procedural and Object-Oriented Programming 705
13.2 Introduction to Classes 712
13.3 Defining an Instance of a Class 717
13.4 Why Have Private Members? 728
13.5 Focus on Software Engineering: Separating Class Specification
from Implementation 729
13.6 Inline Member Functions 735
13.7 Constructors 738
13.8 Passing Arguments to Constructors 742
13.9 Destructors 750
Contents xi
13.10 Overloading Constructors 754
13.11 Private Member Functions 758
13.12 Arrays of Objects 760

13.13 Focus on Problem Solving and Program Design: An OOP Case Study 764
13.14 Focus on Object-Oriented Programming: Creating an Abstract Array
Data Type 771
13.15 Focus on Object-Oriented Design: The Unified Modeling Language (UML) 775
13.16 Focus on Object-Oriented Design: Finding the Classes and Their
Responsibilities 778
CHAPTER 14 More About Classes 801
14.1 Instance and Static Members 801
14.2 Friends of Classes 809
14.3 Memberwise Assignment 814
14.4 Copy Constructors 815
14.5 Operator Overloading 819
14.6 Object Conversion 846
14.7 Aggregation 848
14.8 Focus on Object-Oriented Design: Class Collaborations 854
CHAPTER 15 Inheritance, Polymorphism, and Virtual Functions 871
15.1 What Is Inheritance? 871
15.2 Protected Members and Class Access 880
15.3 Constructors and Destructors in Base and Derived Classes 886
15.4 Redefining Base Class Functions 893
15.5 Class Hierarchies 897
15.6 Polymorphism and Virtual Member Functions 903
15.7 Abstract Base Classes and Pure Virtual Functions 918
15.8 Multiple Inheritance 925
Appendix A: The ASCII Character Set 945
Appendix B: Operator Precedence and Associativity 949
Index 951
Student CD The following appendices are on the accompanying Student CD.
Appendix C: Introduction to Flowcharting
Appendix D: Using UML in Class Design

Appendix E: Namespaces
Appendix F: Writing Managed C++ Code for the .NET Framework
Appendix G: Passing Command Line Arguments
Appendix H: Header File and Library Function Reference
Appendix I: Binary Numbers and Bitwise Operations
Appendix J: Multi-Source File Programs
Appendix K: Stream Member Functions for Formatting
Appendix L: Introduction to Microsoft Visual C++ 2008 Express Edition
Appendix M: Answers to Checkpoints
Appendix N: Answers to Odd Numbered Review Questions
xii
Preface
Welcome to the Brief Version of Starting Out with C++: From Control Structures through
Objects, 6th edition. This book is intended for use in a one or two-semester C++ program-
ming course. Students new to programming, as well as those with prior course work in
other languages, will find this text beneficial. The fundamentals of programming are cov-
ered 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 writ-
ten with clear, easy-to-understand language and it covers all the necessary 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 imple-
ment the features and constructs of C++, but why and when to use them.
Changes in the Sixth Edition
This book’s pedagogy, organization, and clear writing style remain the same as in the pre-
vious edition. Many improvements have been made, which are summarized here:
• Improved Organization in Chapter 4
The section covering the
if/else if
statement has been simplified, and now
appears immediately following the section on nested

if
statements. These sections
have been rewritten to highlight the similarities between an
if/else if
statement
and a nested
if
statement.
• New Chapter on Sorting and Searching Arrays
The bonus chapter on sorting and searching arrays that was previously included
on the Student CD is now included in the book as Chapter 8. The chapter covers
the Bubble Sort, Selection Sort, Linear Search, and Binary Search algorithms.
There is also a section on sorting and searching STL vector objects.
• New In the Spotlight Sections
Many of the chapters have new sections titled In the Spotlight. Each of these pro-
vides a programming problem and a detailed, step-by-step analysis showing the
student how to solve it.
• Online videonotes
An extensive series of online videos have been developed to accompany this
text. Throughout the book, video note icons alert the student to videos covering
Preface xiii
specific topics. Additionally, one Programming Challenge at the end of each chap-
ter now has an accompanying video note explaining how to develop the prob-
lem’s solution. The videos are available at
www.pearsonhighered.com/gaddis.
• Additional Programming Problems
Additional Programming Challenge problems have been added to most chapters.
Several of these are simple games that will challenge and motivate students.
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, some flexibility is provided. The diagram
shown in Figure P-1 suggests possible sequences of instruction.
Chapter 1 covers fundamental hardware, software, and programming concepts. You may
choose to skip this chapter if the class has already mastered those topics. Chapters 2
through 7 cover basic C++ syntax, data types, expressions, selection structures, repetition
structures, functions, and arrays. Each of these chapters builds on the previous chapter
and should be covered in the order presented.
After Chapter 7 has been covered, you may proceed to Chapter 8, or jump to either Chap-
ter 9 or Chapter 12. (If you jump to Chapter 12 at this point, you will need to postpone
sections 12.7, 12.8, and 12.10 until Chapters 9 and 11 have been covered.)
After Chapter 9 has been covered, either of Chapters 10 or 11 may be covered. After
Chapter 11, you may cover Chapters 13 through 15 in sequence.
This text’s approach starts with a firm foundation in structured, procedural programming
before delving fully into object-oriented programming and advanced data structures.
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 programming, problem solving, and software design. The components of pro-
grams, such as key words, variables, operators, and punctuation are covered. The tools of
the trade, such as pseudocode, flow charts, and hierarchy charts are also presented.
Chapter 2: Introduction to C++
This chapter gets the student started in C++ by introducing data types, identifiers, variable
declarations, constants, comments, program output, simple arithmetic operations, and C-
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 pre-standard C++ programs.
xiv Preface
Chapter 3: Expressions and Interactivity
In this chapter the student learns to write programs that input and handle numeric, char-

acter, and C-string data. The use of arithmetic operators and the creation of mathemati-
cal expressions are covered in greater detail, 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.
Chapter 4: Making Decisions
Here the student learns about relational operators, relational expressions and how to con-
trol the flow of a program with the
if
,
if
/
else
, and
if
/
else

if
statements. The condi-
tional operator and the
switch
statement are also covered. Crucial applications of these
constructs are covered, such as menu-driven programs and the validation of input.
Figure P-1
Chapter 8
Searching And
Sorting Arrays
Chapter 9
Pointers


Chapter 10
Characters, Strings,
and the string Class


Chapter 12
Advanced File
Operations*

Chapters 2–7
Basic Language
Elements
Chapter 11
Structures
Chapter 13
Introduction to
Classes

Chapter 14
More About Classes

Chapter 15
Inheritance and
Polymorphism
*A few subtopics in
Chapter 12 require
Chapters 9 and 11.
Chapter 1
Introduction

Preface xv
Chapter 5: Looping
This chapter covers repetition control structures. The
while
loop,
do
-
while
loop, and
for
loop are taught, along with common uses for these devices. Counters, accumulators, run-
ning totals, sentinels, and other application-related topics are discussed. A section on file I/O
discusses how to use a loop to read from a file until the end of the file is encountered.
Chapter 6: Functions
In this chapter the student learns how and why to modularize programs, using both
void
and value returning functions. Argument passing is covered, with emphasis on when argu-
ments 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: 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.
Chapter 8: Sorting and Searching Arrays
Here the student learns the basics of sorting arrays and searching for data stored in them.
The chapter covers the Bubble Sort, Selection Sort, Linear Search, and Binary Search algo-

rithms. There is also a section on sorting and searching STL
vector
objects.
Chapter 9: Pointers
This chapter explains how to use pointers. Pointers are compared to and contrasted with
reference variables. Other topics include pointer arithmetic, initialization of pointers, rela-
tional comparison of pointers, pointers and arrays, pointers and functions, dynamic mem-
ory allocation, and more.
Chapter 10: Characters, C-strings, and the Standard string Class
This chapter focuses on library functions that manipulate or test characters or strings. A
review of the internal storage of C-strings is given. An extensive discussion of the standard
string
class is also presented.
Chapter 11: Structured Data
The student is introduced to abstract data types and taught how to create them using struc-
tures, unions, and enumerated data types. Discussions and examples include using pointers
to structures, passing structures to functions, and returning structures from functions.
xvi Preface
Chapter 12: Advanced File 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 contents. Advanced output formatting is also covered.
Chapter 13: Introduction to Classes
The student now shifts focus to the object-oriented paradigm. This chapter covers the
fundamental concepts of classes. Member variables and functions are discussed. The
student learns about private and public access specifications, and reasons to use each.
The topics of constructors, overloaded constructors, and destructors are also presented.
The chapter presents a section modeling classes with UML, and how to find the classes
in a particular problem.
Chapter 14: More About Classes

This chapter continues the study of classes. Static members, friends, memberwise assign-
ment, and copy constructors are discussed. The chapter also includes in-depth sections on
operator overloading, object conversion, and object aggregation. There is also a section
on class collaborations and the use of CRC cards.
Chapter 15: Inheritance and Polymorphism
The study of classes continues in this chapter with the subjects of inheritance, polymor-
phism, and virtual member functions. The topics covered include base and derived class
constructors and destructors, virtual member functions, base class pointers, static and
dynamic binding, multiple inheritance, and class hierarchies.
Appendix A: ASCII Character Set
A list of the ASCII and Extended ASCII characters and their codes.
Appendix B: Operator Precedence and Associativity
A chart showing the C++ operators and their precedence.
The following appendices are on the accompanying Student CD:
Appendix C: Introduction to Flowcharting
A brief introduction to flowcharting. This tutorial discusses sequence, selection, case, rep-
etition, and module structures.
Appendix D: Using UML in Class Design
This appendix shows the student how to use the Unified Modeling Language to design
classes. Notation for showing access specification, data types, parameters, return values,
overloaded functions, composition, and inheritance are included.
Preface xvii
Appendix E: Namespaces
This appendix explains namespaces and their purpose. Examples showing how to define a
namespace and access its members are given.
Appendix F: Writing Managed C++ Code for the .NET Framework
This appendix introduces the student to the concepts surrounding managed C++ in
Microsoft’s .NET environment.
Appendix G: Passing Command Line Arguments
Teaches the student how to write a C++ program that accepts arguments from the com-

mand line. This appendix will be useful to students working in a command line environ-
ment, such as Unix, Linux, or the Windows MS-DOS prompt console.
Appendix H: Header File and Library Function Reference
This appendix provides a reference for the C++ library functions and header files discussed
in the book.
Appendix I: Binary Numbers and Bitwise Operations
A guide to the C++ bitwise operators, as well as a tutorial on the internal storage of integers.
Appendix J: Multi-Source File Programs
Provides a tutorial on creating programs that consist of multiple source files. Function
header files, class specification files, and class implementation files are discussed.
Appendix K: Stream Member Functions for Formatting
Covers stream member functions for formatting such as setf.
Appendix L: Introduction to Microsoft Visual C++ 2008 Express Edition
A tutorial on how to start a project in Microsoft Visual C++ 2008 Express Edition, com-
pile a program, save source files, and more.
Appendix M: Answers to Checkpoints
Students may test their own progress by comparing their answers to the checkpoint exer-
cises against this appendix. The answers to all Checkpoints are included.
Appendix N: Answers to Odd-Numbered Review Questions
Another tool that students can use to gauge their progress.
xviii Preface
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 300 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.
In the Spotlight Each of these sections provides a programming problem and a
detailed, step by step analysis showing the student how to solve
it.
videonotes A series of online videos, developed specifically for this book,
are available for viewing at
rsonhighered.
com/gaddis
. Icons appear throughout the text alerting the
student to videos about specific topics.
Checkpoints Checkpoints are questions placed throughout each chapter as a
self-test study aid. Answers for all Checkpoint questions are
provided on the student 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 relevant 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
and Exercises

Each chapter presents a thorough and diverse set of review
questions, such as fill-in-the-blank and short answer, that check
the student’s mastery 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. Answers to the odd
numbered review questions and review exercises are provided
on the student CD.
Preface xix
Supplements
Student CD
This CD includes:
• Turbo C++ 2006 Explorer Edition
• Answers to all Checkpoint questions (Appendix M)
• Answers to all odd-numbered Review Questions and Exercises (Appendix N)
• Complete source code for every program included in the book
• Additional case studies, complete with source code
• A full set of appendices that accompany the book
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
Professors should contact their campus Addison-Wesley representative for the specific
ISBN to order this book packaged with Microsoft Visual C++ 2008 Express Edition.
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
Programming
Challenges
Each chapter offers a pool of programming exercises designed
to solidify the student’s knowledge of the topics currently being

studied. In most cases the assignments present real-world
problems to be solved. When applicable, these exercises include
input validation 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.
C++ Quick
Reference Guide
For easy access, a quick reference guide to the C++ language is
printed on the last page of the book and the inside back cover.
xx Preface
Programming 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 com-
piler error messages. Instructors can track each student’s progress on Programming Chal-
lenges 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. Subscriptions can also be purchased online. For more information visit
http://
www.mycodemate.com
, or contact your campus Addison-Wesley representative.
Instructor Resources
The following supplements are available to qualified instructors only:
• 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
Visit the Addison-Wesley Instructor Resource Center (
/>irc
) or send an email to for information on how to access them.
Textbook Web site
A Web site for the Starting Out with C++ series of books is located at the following URL:
www.pearsonhighered.com/gaddisbooks
Get this book the way you want it!
This book is part of Pearson Education’s custom database for Computer Science textbooks.
Use our online PubSelect system to select just the chapters you need from this, and other,
Pearson Education CS textbooks. You can edit the sequence to exactly match your course
organization and teaching approach. Visit
www.pearsoncustom.com/cs for details.
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++: From Control Structures through Objects
• Starting Out with C++: Early Objects
• Brief Version of Starting Out with C++: From Control Structures through
Objects.
Preface xxi
The following chart will help you determine which book is right for your course.
Acknowledgments
There have been many helping hands in the development and publication of this text. We
would like to thank the following faculty reviewers for their helpful suggestions and
expertise.
 FROM CONTROL STRUCTURES
THROUGH OBJECTS

 BRIEF VERSION

EARLY OBJECTS
LATE INTRODUCTION OF OBJECTS
Classes are introduced in Chapter 13, after control
structures, functions, arrays, and pointers. Advanced
OOP topics, such as inheritance and polymorphism,
are covered in Chapters 14 and 15.
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 full text.
Recursion is covered after stacks and queues, but
before binary trees. These topics are not covered in
the brief text.
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.
Ahmad Abuhejleh
University of Wisconsin, River Falls
Robert Baird
Salt Lake Community College
David Akins
El Camino College
Don Biggerstaff
Fayetteville Technical Community College
Steve Allan
Utah State University
Michael Bolton
Northeastern Oklahoma State University
Vicki Allan
Utah State University
Bill Brown
Pikes Peak Community College
Karen M. Arlien
Bismark State College
Charles Cadenhead
Richland Community College
Mary Astone

Troy University
Randall Campbell
Morningside College
Ijaz A. Awan
Savannah State University
Wayne Caruolo
Red Rocks Community College
xxii Preface
Cathi Chambley-Miller
Aiken Technical College
Mike Holland
Northern Virginia Community College
C.C. Chao
Jacksonville State University
Mary Hovik
Lehigh Carbon Community College
Joseph Chao
Bowling Green State University
Richard Hull
Lenoir-Rhyne College
Royce Curtis
Western Wisconsin Technical College
Chris Kardaras
North Central College
Joseph DeLibero
Arizona State University
Willard Keeling
Blue Ridge Community College
Jeanne Douglas
University of Vermont

A.J. Krygeris
Houston Community College
Michael Dowell
Augusta State U
Sheila Lancaster
Gadsden State Community College
Judy Etchison
Southern Methodist University
Ray Larson
Inver Hills Community College
Dennis Fairclough
Utah Valley State College
Jennifer Li
Ohlone College
Richard Flint
North Central College
Norman H. Liebling
San Jacinto College
Ann Ford
Florida State University
Zhu-qu Lu
University of Maine, Presque Isle
James Gifford
University of Wisconsin, Stevens Point
Heidar Malki
University of Houston
Leon Gleiberman
Touro College
Debbie Mathews
J. Sargeant Reynolds

Ranette Halverson, Ph.D.
Midwestern State University
Rick Matzen
Northeastern State University
Carol Hannahs
University of Kentucky
Robert McDonald
East Stroudsburg University
Dennis Heckman
Portland Community College
James McGuffee
Austin Community College
Ric Heishman
George Mason University
Dean Mellas
Cerritos College
Michael Hennessy
University of Oregon
Lisa Milkowski
Milwaukee School of Engineering
Ilga Higbee
Black Hawk College
Marguerite Nedreberg
Youngstown State University
Patricia Hines
Brookdale Community College
Lynne O’Hanlon
Los Angeles Pierce College
Preface xxiii
I also want to thank everyone at Pearson Addison-Wesley for making the Starting Out

with series so successful. I have worked so closely with the team at Pearson Adddison-
Wesley that I consider them among my closest friends. I am extremely grateful that
Michael Hirsch is my editor. Stephanie Sellinger, editorial assistant, managed the revision
of this book and made the entire process a pleasure. I am also thankful to have Erin Davis
Frank Paiano
Southwestern Community College
Caroline St. Claire
North Central College
Theresa Park
Texas State Technical College
Kirk Stephens
Southwestern Community College
Mark Parker
Shoreline Community College
Cherie Stevens
South Florida Community College
Tino Posillico
SUNY Farmingdale
Dale Suggs
Campbell University
Frederick Pratter
Eastern Oregon University
Mark Swanson
Red Wing Technical College
Susan L. Quick
Penn State University
Martha Tillman
College of San Mateo
Alberto Ramon
Diablo Valley College

Ralph Tomlinson
Iowa State University
Bazlur Rasheed
Sault College of Applied Arts and Technology
David Topham
Ohlone College
Farshad Ravanshad
Bergen Community College
Robert Tureman
Paul D. Camp Community College
Dolly Samson
Weber State University
Arisa K. Ude
Richland College
Ruth Sapir
SUNY Farmingdale
Peter van der Goes
Rose State College
Jason Schatz
City College of San Francisco
Stewart Venit
California State University, Los Angeles
Dr. Sung Shin
South Dakota State University
Judy Walters
North Central College
Bari Siddique
University of Texas at Brownsville
John H. Whipple
Northampton Community College

William Slater
Collin County Community College
Aurelia Williams
Norfolk State University
Shep Smithline
University of Minnesota
Vida Winans
Illinois Institute of Technology

×