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

Contents i What’s New with This Edition Teach Yourself ANSI C++ in 21 Days, Premier Edition, is

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 (5.88 MB, 875 trang )

i
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
What’s New with This Edition
Teach Yourself ANSI C++ in 21 Days, Premier Edition, is a new edition of the
international bestseller, Teach Yourself C++ in 21 Days. This Premier Edition offers
more than just 21 days of learning ANSI/ISO C++.
Major changes throughout this edition have been made to reflect the latest ANSI/
ISO C++ draft standard. In addition, seven new lessons, referred to as “Bonus Days,”
have been added to provide you with additional information for creating more
sophisticated programs. The Bonus Day lessons are not required reading in order
for you to learn to program in C++. As a matter of fact, on the very first day you will
write a simple C++ program.
On Bonus Day 22, “Advanced C++ Features,” you learn to use a collection of
specialized ANSI C++ tools that many programmers don’t even realize exist. These
tools are not essential for every C++ programmer to know but are indispensable in
many circumstances.
Bonus Day 23, “More About Streams,” covers some of the more advanced streams
programming techniques. After completing this lesson, you will have all you need
to create new manipulators for the stream classes you learn to create on Day 16. You
will also learn a great deal about other streams programming techniques that space
would not allow us to cover on Day 16.
On Bonus Day 24, “Object-Oriented Design,” you learn more about this important
subject. Without object-oriented design techniques, C++ is “just another C” with
few advantages over its predecessor. This lesson helps you think in a way that builds
on the object-oriented design paradigm.
Bonus Days 25 and 26, “Data Structures” and “Simple Sorting and Searching
Algorithms,” respectively, introduce you to the inner sanctum of computer science.
On these two days you learn how to solve several common categories of problems.
“Common Mistakes and Basic Debugging,” on Bonus Day 27, is designed to help
you avoid some of the common mistakes that many beginning programmers make.


Not all errors can be avoided, but with this lesson you should more quickly recognize
many errors by their categories and more quickly find their solutions.
The final day of the bonus week, “What’s Next?,” gives you some insight on where
to turn when you run into a question that this book doesn’t seem to answer. It also
provides the resources you need to further improve your C++ programming skills.
Teach Yourself ANSI C++ in 21 Days
ii
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
iii
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
teach
yourself
ANSI C++
in 21 days,
Premier Edition
Teach Yourself ANSI C++ in 21 Days
iv
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
v
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Jesse Liberty
J. Mark Hord
teach yourself
ANSI C++
in 21 days, Premier Edition
201 West 103rd Street
Indianapolis, Indiana 46290
PUBLISHING

S MS
Teach Yourself ANSI C++ in 21 Days
vi
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Acquisitions Editor
Bradley L. Jones
Development Editor
Anthony Amico
Production Editor
Ryan Rader
Copy Editors
Howard Jones
Marla Reece
Technical Reviewer
Justin Bell
John W. Charlesworth
Editorial Coordinator
Bill Whitmer
Technical Edit Coordinator
Lynette Quinn
Formatter
Frank Sinclair
Editorial Assistants
Sharon Cox
Andi Richter
Rhonda Tinch-Mize
Cover Designer
Tim Amrhein
Book Designer
Gary Adair

Copy Writer
Peter Fuller
Production Team Supervisor
Brad Chinn
Production
Mary Ann Abramson,
Mona Brown, Georgiana Briggs,
Michael Brummitt, Jeanne Clark,
Terri Edwards, George Hamlin,
Sonya Hart, Mike Henry,
Ayanna Lacey, Kevin Laseau,
Paula Lowell, Donna Martin,
Casey Price, Nancy Price,
Brian-Kent Proffitt, Beth Rago,
SA Springer, Tim Taylor,
Andrew Stone, Mark Walchle
Todd Wente, Colleen Williams
Copyright  1996 by Sams Publishing
PREMIER EDITION
All rights reserved. No part of this book shall be reproduced, stored in a
retrieval system, or transmitted by any means, electronic, mechanical,
photocopying, recording, or otherwise, without written permission from the
publisher. No patent liability is assumed with respect to the use of the
information contained herein. Although every precaution has been taken in
the preparation of this book, the publisher and author assume no responsi-
bility for errors or omissions. Neither is any liability assumed for damages
resulting from the use of the information contained herein. For informa-
tion, address Sams Publishing, 201 W. 103rd St., Indianapolis, IN 46290.
International Standard Book Number: 0-672-30887-6
Library of Congress Catalog Card Number: 95-72920

99 98 97 96 4 3 2 1
Interpretation of the printing code: the rightmost double-digit number is
the year of the book’s printing; the rightmost single-digit, the number of the
book’s printing. For example, a printing code of 96-1 shows that the first
printing of the book occurred in 1996.
Composed in Agaramond and MCPdigital by Macmillan Computer Publishing
Printed in the United States of America
All terms mentioned in this book that are known to be trademarks or service
marks have been appropriately capitalized. Sams Publishing cannot attest to
the accuracy of this information. Use of a term in this book should not be
regarded as affecting the validity of any trademark or service mark.
Publisher and President
Richard K. Swadley
Acquisitions Manager
Greg Wiegand
Development Manager
Dean Miller
Managing Editor
Cindy Morrow
Marketing Manager
Gregg Bushyeager
vii
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Overview
Week 1 At A Glance 1
1 Getting Started 3
2 The Parts of a Program 19
3 Variables and Constants 31
4 Expressions and Statements 55

5 Functions 87
6 Basic Classes 123
7 More Program Flow 155
Week 1 In Review 187
Week 2 At A Glance 193
8 Pointers 195
9 References 223
10 Advanced Functions 257
11 Arrays 293
12 Inheritance 329
13 Multiple Inheritance 361
14 Special Classes and Functions 395
Week 2 In Review 421
Week 3 At A Glance 431
15 Advanced Inheritance 433
16 Streams 469
17 The Preprocessor 509
18 Creating Reusable Code 537
19 Templates 551
20 Exceptions and Error Handling 581
21 Working with Multiple Files for Large Programs 609
Week 3 In Review 625
Teach Yourself ANSI C++ in 21 Days
viii
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Bonus Days At A Glance 635
22 Coding Styles and Idioms 637
23 More About Streams 659
24 Object-Oriented Design 673
25 Data Structures 683

26 Simple Sorting and Searching Algorithms 701
27 Common Mistakes and Basic Debugging 721
28 What’s Next? 733
Appendixes
A Operator Precedence 741
B C++ Keywords 745
C Binary and Hexadecimal 747
D Answers 757
Index 831
ix
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Contents
Week 1 At A Glance 1
A Note to C Programmers .......................................................................... 2
Where You Are Going ................................................................................ 2
Day 1 Getting Started 3
A Brief History of C++ ............................................................................... 3
ANSI/ISO C++ .......................................................................................... 5
What Is a Program? .................................................................................... 5
Sophisticated Tools for Sophisticated Programming ................................... 6
Procedural, Structured, and Object-Oriented Programming .................. 6
C++ and Object-Oriented Programming ............................................... 8
How C++ Evolved ................................................................................. 9
Should I Learn C First? ........................................................................ 10
Preparing to Program ............................................................................... 10
Your Development Environment.............................................................. 11
Compiling the Source Code ..................................................................... 12
Creating an Executable File with the Linker ............................................. 12
The Development Cycle ........................................................................... 13

HELLO.CPP: Your First C++ Program .................................................... 14
Compile Errors ......................................................................................... 15
Summary .................................................................................................. 16
Q&A ........................................................................................................ 16
Quiz ......................................................................................................... 17
Exercises ................................................................................................... 17
2 The Parts of a C++ Program 19
The Parts of a Simple Program ................................................................. 19
A Brief Look at
cout
................................................................................. 21
Comments................................................................................................ 22
Types of Comments ............................................................................ 23
Using Comments ................................................................................. 23
Comments at the Top of Each File ...................................................... 24
A Final Word of Caution About Comments ........................................ 25
Functions ................................................................................................. 26
Using Functions .................................................................................. 27
Summary .................................................................................................. 29
Q&A ........................................................................................................ 29
Quiz ......................................................................................................... 29
Exercises ................................................................................................... 30
Teach Yourself ANSI C++ in 21 Days
x
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
3 Variables and Constants 31
What Is a Variable?................................................................................... 31
Setting Aside Memory ......................................................................... 32
Size of Integers..................................................................................... 33
Signed and Unsigned ........................................................................... 34

Fundamental Variable Types ............................................................... 35
Defining a Variable................................................................................... 36
Case Sensitivity .................................................................................... 37
Keywords ............................................................................................. 38
Creating More Than One Variable
at a Time................................................................................................ 39
Assigning Values to Your Variables ........................................................... 39
typedef
.................................................................................................... 40
Choosing Between
short
and
long
........................................................... 41
Wrapping Around in Unsigned Integers .............................................. 42
Wrapping Around a Signed Integer ..................................................... 43
Characters ................................................................................................ 43
chars
and Numbers ............................................................................. 44
Special Printing Characters .................................................................. 44
Constants ................................................................................................. 46
Literal Constants.................................................................................. 46
Symbolic Constants ............................................................................. 46
Enumerated Constants ............................................................................. 49
Summary .................................................................................................. 50
Q&A ........................................................................................................ 51
Quiz ......................................................................................................... 52
Exercises ................................................................................................... 53
4 Expressions and Statements 55
Statements ................................................................................................ 56

Whitespace .......................................................................................... 56
Blocks and Compound Statements ...................................................... 57
Expressions ............................................................................................... 57
Operators ................................................................................................. 59
Assignment Operator ........................................................................... 59
Mathematical Operators ...................................................................... 60
Integer Division and Modulus ............................................................. 60
Combining the Assignment and Mathematical Operators ........................ 61
Increment and Decrement ........................................................................ 62
Prefix and Postfix ................................................................................. 62
Precedence................................................................................................ 64
Nesting Parentheses .................................................................................. 64
The Bitwise Operators .............................................................................. 65
Operator AND .................................................................................... 66
Operator OR ....................................................................................... 67
Operator Exclusive OR ........................................................................ 67
xi
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
The Complement Operator ................................................................. 67
Shift Operators .................................................................................... 67
Setting Bits .......................................................................................... 67
Clearing Bits ........................................................................................ 68
Flipping Bits ........................................................................................ 68
Fast Math Through the Power of the Bit ............................................. 68
The Nature of Truth ................................................................................ 69
Relational Operators ................................................................................. 69
The if Statement ....................................................................................... 70
else
..................................................................................................... 73

Advanced
if
Statements ...................................................................... 75
Using Braces in Nested
if
Statements.................................................. 76
Logical Operators ..................................................................................... 79
Logical AND ....................................................................................... 79
Logical OR .......................................................................................... 80
Logical NOT ....................................................................................... 80
Relational Precedence ............................................................................... 80
More About Truth and Falsehood ............................................................ 81
Conditional (Ternary) Operator ............................................................... 82
Summary .................................................................................................. 84
Q&A ........................................................................................................ 84
Quiz ......................................................................................................... 85
Exercises ................................................................................................... 85
5 Functions 87
What Is a Function? ................................................................................. 88
Declaring and Defining Functions............................................................ 88
Declaring the Function ........................................................................ 89
Function Prototypes ............................................................................ 89
Defining the Function ......................................................................... 91
Execution of Functions ........................................................................ 93
Local Variables ......................................................................................... 93
Global Variables ....................................................................................... 95
More on Local Variables ........................................................................... 97
Function Statements ................................................................................. 99
Function Arguments ................................................................................. 99
Using Functions as Parameters to Functions ........................................ 99

Parameters Are Local Variables ............................................................... 100
Return Values ......................................................................................... 101
Default Parameters ................................................................................. 103
Overloading Functions ........................................................................... 106
Special Topics......................................................................................... 108
Inline Functions ................................................................................ 109
Recursion........................................................................................... 111
Summary ................................................................................................ 114
Q&A ...................................................................................................... 114
Teach Yourself ANSI C++ in 21 Days
xii
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Quiz ....................................................................................................... 115
Exercises ................................................................................................. 115
Extra Credit............................................................................................ 116
How Functions Work ........................................................................ 117
Levels of Abstraction.......................................................................... 117
Partitioning RAM .............................................................................. 117
The Stack and Functions ................................................................... 120
6 Basic Classes 123
Creating New Types ............................................................................... 124
Why Create a New Type? .................................................................. 124
Classes and Members .............................................................................. 124
Declaring a Class ............................................................................... 125
Classes Versus Objects ....................................................................... 126
Defining an Object ............................................................................ 126
Accessing Class Members........................................................................ 126
Assign to Objects, Not to Classes....................................................... 126
If It’s Not Declared, Your Class Won’t Have It ................................. 127
Private Versus Public .............................................................................. 128

Make Member Data Private ............................................................... 130
Privacy Versus Security ...................................................................... 132
Implementing Class Methods ................................................................. 134
Constructors and Destructors ................................................................. 136
Default Constructors and Destructors................................................ 137
const
Member Functions ....................................................................... 140
Interface Versus Implementation ............................................................ 141
Where to Put Class Declarations and Method Definitions...................... 143
Inline Implementation............................................................................ 145
Classes with Other Classes
as Member Data ................................................................................... 147
Structures ............................................................................................... 150
Why Two Keywords Do the Same Thing .......................................... 151
Summary ................................................................................................ 152
Q&A ...................................................................................................... 152
Quiz ....................................................................................................... 153
Exercises ................................................................................................. 154
7 More Program Flow 155
Looping .................................................................................................. 156
The Roots of Looping
goto
............................................................... 156
Why
goto
Is Shunned........................................................................ 157
while
Loops ........................................................................................... 157
More Complicated
while

Statements................................................. 159
continue
and
break
........................................................................... 160
The
while (true)
Loop .................................................................... 163
do…while
Loops ...................................................................................... 164
The
do…while
Loop ................................................................................ 165
xiii
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
for
Loops ............................................................................................... 167
Advanced
for
Loops .......................................................................... 169
Empty
for
Loops ............................................................................... 172
Nested Loops ..................................................................................... 173
Scoping in Loops ............................................................................... 174
Summing Up Loops ............................................................................... 174
switch
Statements .................................................................................. 177
Using a

switch
Statement with a Menu ............................................. 180
Summary ................................................................................................ 183
Q&A ...................................................................................................... 183
Quiz ....................................................................................................... 184
Exercises ................................................................................................. 184
Week 1 In Review 187
Week In Review ..................................................................................... 192
Week 2 At A Glance 193
Where You Are Going ............................................................................ 193
Day 8 Pointers 195
What Is a Pointer? .................................................................................. 195
Storing the Address in a Pointer......................................................... 197
The Indirection Operator .................................................................. 199
Pointers, Addresses, and Variables...................................................... 200
Manipulating Data by Using Pointers ................................................ 201
Examining the Address ...................................................................... 202
Why Would You Use Pointers? .............................................................. 204
The Stack and the Free Store .................................................................. 204
new
..................................................................................................... 206
delete
............................................................................................... 206
Memory Leaks ................................................................................... 208
Creating Objects on the Free Store .................................................... 209
Deleting Objects ................................................................................ 210
Accessing Data Members ................................................................... 211
Member Data on the Free Store......................................................... 212
The
this

Pointer ............................................................................... 213
Stray or Dangling Pointers...................................................................... 215
const
Pointers ........................................................................................ 218
const
Pointers and
const
Member Functions......................................... 218
const this
Pointers ............................................................................... 220
Summary ................................................................................................ 220
Q&A ...................................................................................................... 221
Quiz ....................................................................................................... 221
Exercises ................................................................................................. 221
9 References 223
What Is a Reference?............................................................................... 223
Requesting the Address of a Reference .................................................... 225
Teach Yourself ANSI C++ in 21 Days
xiv
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
What Can Be Referenced? ...................................................................... 228
Null Pointers and Null References .......................................................... 230
Passing Function Arguments by Reference.............................................. 230
Making
swap()
Work with Pointers .................................................. 231
Implementing
swap()
with References ............................................... 233
Understanding Function Headers and Prototypes................................... 234

Returning Multiple Values ..................................................................... 235
Returning Values by Reference .......................................................... 237
Passing by Reference for Efficiency ......................................................... 238
Passing a
const
Pointer ...................................................................... 241
References as an Alternative ............................................................... 243
Choosing Between References and Pointers ............................................ 245
Pointer References .................................................................................. 246
Mixing References and Pointers.............................................................. 248
Don’t Return a Reference to an Object that Isn’t in Scope! .................... 249
Returning a Reference to an Object
on the Heap ......................................................................................... 251
Who Has the Pointer? ............................................................................ 253
Summary ................................................................................................ 253
Q&A ...................................................................................................... 254
Quiz ....................................................................................................... 254
Exercises ................................................................................................. 254
10 Advanced Functions 257
Overloaded Member Functions .............................................................. 257
Using Default Values .............................................................................. 260
Choosing Between Default Values and Overloaded Functions................ 262
The Default Constructor ........................................................................ 262
Overloading Constructors ...................................................................... 263
Initializing Objects ................................................................................. 264
The Copy Constructor ........................................................................... 265
Operator Overloading ............................................................................ 270
Writing an Increment Function ......................................................... 271
Overloading the Prefix Operator........................................................ 272
Returning Types in Overloaded Operator Functions ......................... 273

Returning Nameless Temporaries ...................................................... 274
Using the
this
Pointer ...................................................................... 276
Overloading the Postfix Operator ...................................................... 277
operator+
.......................................................................................... 279
Overloading
operator+
...................................................................... 281
Issues in Operator Overloading.......................................................... 282
Limitations on Operator Overloading................................................ 283
What to Overload .............................................................................. 283
operator=
.......................................................................................... 284
Conversion Operators............................................................................. 286
Operator
unsigned short()
.............................................................. 288
xv
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Summary ................................................................................................ 289
Q&A ...................................................................................................... 290
Quiz ....................................................................................................... 291
Exercises ................................................................................................. 291
11 Arrays 293
What Is an Array? ................................................................................... 293
Array Elements ....................................................................................... 294
Writing Past the End of an Array............................................................ 295

Fence Post Errors .................................................................................... 298
Initializing Arrays ................................................................................... 298
Declaring Arrays ..................................................................................... 299
Arrays of Objects .................................................................................... 301
Multidimensional Arrays ........................................................................ 302
Initializing Multidimensional Arrays....................................................... 303
A Word About Memory ......................................................................... 304
Arrays of Pointers ................................................................................... 305
Declaring Arrays on the Free Store ......................................................... 306
A Pointer to an Array Versus an Array of Pointers .................................. 307
Pointers and Array Names ...................................................................... 307
Deleting Arrays on the Free Store ........................................................... 309
char
Arrays ............................................................................................. 310
strcpy()
and
strncpy()
........................................................................ 312
String Classes.......................................................................................... 313
Linked Lists and Other Structures .......................................................... 320
Array Classes........................................................................................... 325
Summary ................................................................................................ 326
Q&A ...................................................................................................... 327
Quiz ....................................................................................................... 327
Exercises ................................................................................................. 328
12 Inheritance 329
What Is Inheritance? ............................................................................... 329
Inheritance and Derivation ................................................................ 330
The Animal Kingdom ........................................................................ 331
The Syntax of Derivation................................................................... 331

Private Versus Protected Class Members................................................. 333
Constructors and Destructors ................................................................. 335
Passing Arguments to Base Constructors............................................ 337
Overriding Functions ............................................................................. 341
Hiding the Base Class Method........................................................... 343
Calling the Base Method.................................................................... 345
Virtual Methods ..................................................................................... 346
You Can’t Get There from Here ........................................................ 351
Slicing................................................................................................ 351
Virtual Destructors ............................................................................ 353
Virtual Copy Constructors................................................................. 354
The Cost of Virtual Methods ............................................................. 357
Teach Yourself ANSI C++ in 21 Days
xvi
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Summary ................................................................................................ 357
Q&A ...................................................................................................... 358
Quiz ....................................................................................................... 359
Exercises ................................................................................................. 359
13 Multiple Inheritance 361
Problems with Single Inheritance ........................................................... 361
Percolating Upward ........................................................................... 365
The Parts of a Multiple Inheritance Object........................................ 368
Constructors in Multiple Inheritance Objects .................................... 369
Ambiguity Resolution ........................................................................ 371
Inheriting from a Shared Base Class ................................................... 372
Virtual Inheritance............................................................................. 376
Problems with Multiple Inheritance................................................... 379
Mixins and Capabilities Classes ......................................................... 380
Abstract Data Types ............................................................................... 381

Pure Virtual Functions....................................................................... 384
Implementing Pure Virtual Functions ............................................... 385
Complex Hierarchies of Abstraction .................................................. 389
Which Types Are Abstract?................................................................ 392
Summary ................................................................................................ 393
Q&A ...................................................................................................... 393
Quiz ....................................................................................................... 394
Exercises ................................................................................................. 394
14 Special Classes and Functions 395
Static Member Data ............................................................................... 395
Static Member Functions ....................................................................... 400
Pointers to Functions.............................................................................. 402
Why Use Function Pointers? ............................................................. 406
Arrays of Pointers to Functions .......................................................... 408
Passing Pointers to Functions to Other Functions ............................. 410
Using
typedef
with Pointers to Functions ......................................... 412
Pointers to Member Functions ............................................................... 413
Arrays of Pointers to Member Functions............................................ 415
Summary ................................................................................................ 417
Q&A ...................................................................................................... 418
Quiz ....................................................................................................... 418
Exercises ................................................................................................. 419
Week 2 In Review 421
Week 3 At A Glance 431
Where You Are Going ............................................................................ 431
Day 15 Advanced Inheritance 433
Containment .......................................................................................... 433
Accessing Members of the Contained Class ....................................... 439

xvii
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Filtering Access to Contained Members ............................................. 439
Cost of Containment ......................................................................... 440
Copying by Value .............................................................................. 442
Delegation Versus Implemented in
Terms of .............................................................................................. 443
Delegation ......................................................................................... 444
Private Inheritance.................................................................................. 449
Friend Classes ......................................................................................... 453
friend
Functions.................................................................................... 460
friend
Functions and Operator Overloading ......................................... 460
Overloading the Insertion Operator........................................................ 463
Summary ................................................................................................ 465
Q&A ...................................................................................................... 465
Quiz ....................................................................................................... 466
Exercises ................................................................................................. 466
16 Streams 469
Overview of Streams ............................................................................... 469
Encapsulation .................................................................................... 470
Buffering ........................................................................................... 471
Streams and Buffers ................................................................................ 473
Standard I/O Objects ............................................................................. 474
Redirection ............................................................................................. 474
Input Using
cin
...................................................................................... 475

Strings ............................................................................................... 476
String Problems ................................................................................. 477
operator>>
Returns a Reference to an
istream
Object ...................... 479
Other Member Functions of
cin
............................................................ 480
Single Character Input ....................................................................... 480
Getting Strings from Standard Input ................................................. 482
Using
cin.ignore()
.......................................................................... 485
peek()
and
putback()
....................................................................... 486
Output with
cout
................................................................................... 487
Flushing the Output .......................................................................... 487
Related Functions ................................................................................... 488
Manipulators, Flags, and Formatting Instructions .................................. 489
Using
cout.width()
.......................................................................... 490
Setting the Fill Characters .................................................................. 491
Set Flags ............................................................................................ 491
Streams Versus the

printf()
Function ................................................... 493
File Input and Output ............................................................................ 495

ofstream
............................................................................................... 495
Condition States ................................................................................ 496
Opening Files for Input and Output.................................................. 496
Changing the Default Behavior of
ofstream
on Open ....................... 498
Binary Versus Text Files ......................................................................... 500
Command-Line Processing ..................................................................... 502
Teach Yourself ANSI C++ in 21 Days
xviii
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Summary ................................................................................................ 505
Q&A ...................................................................................................... 506
Quiz ....................................................................................................... 506
Exercises ................................................................................................. 507
17 The Preprocessor 509
The Preprocessor and the Compiler ........................................................ 509
Seeing the Intermediate Form................................................................. 510
Using
#define
........................................................................................ 510
Using
#define
for Constants ............................................................. 510
Using

#define
for Tests ..................................................................... 511
The
#else
Precompiler Command .................................................... 511
The
#error
Directive.............................................................................. 512
The
#pragma
Directive ............................................................................ 513
Inclusion and Inclusion Guards .............................................................. 513
Defining on the Command Line........................................................ 514
Undefining ........................................................................................ 514
Conditional Compilation .................................................................. 516
Macro Functions .................................................................................... 516
Why All the Parentheses? ................................................................... 517
Macros Versus Functions and Templates ........................................... 519
Inline Functions ..................................................................................... 519
String Manipulation ............................................................................... 521
Stringizing ......................................................................................... 521
Concatenation ................................................................................... 521
Predefined Macros .................................................................................. 522
assert()
................................................................................................ 522
Debugging with
assert()
................................................................. 524
assert()
Versus Exceptions............................................................... 524

Side Effects ........................................................................................ 525
Class Invariants .................................................................................. 525
Printing Interim Values ..................................................................... 529
Debugging Levels .............................................................................. 531
Summary ................................................................................................ 534
Q&A ...................................................................................................... 535
Quiz ....................................................................................................... 535
Exercises ................................................................................................. 536
18 Creating Reusable Code 537
Remember Code Reuse........................................................................... 538
Avoid Literal Constants ..................................................................... 538
Encapsulate the Details ...................................................................... 539
Comment on the Logic...................................................................... 539
Remember Code Maintenance ............................................................... 541
The Power of Seven ........................................................................... 541
Document the Initial Code and Changes ........................................... 541
Develop a Consistent Coding Style.................................................... 542
Develop a Maintenance Strategy ........................................................ 545
xix
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Remember Code Portability ................................................................... 546
Adhere to the ANSI/ISO Standard .................................................... 547
Think Globally .................................................................................. 548
Summary ................................................................................................ 549
Q&A ...................................................................................................... 549
Quiz ....................................................................................................... 550
Exercises ................................................................................................. 550
19 Templates 551
What are Templates? .............................................................................. 551

Parameterized Types ............................................................................... 552
Template Definition ............................................................................... 552
Using the Name................................................................................. 554
Implementing the Template .............................................................. 554
Template Functions................................................................................ 558
Templates and Friends............................................................................ 558
Nontemplate Friend Classes and Functions ....................................... 559
General Template Friend Class or Function ...................................... 561
A Type-Specific Template Friend Class or Function .......................... 563
Using Template Items ............................................................................ 564
Specialized Functions......................................................................... 567
Static Members and Templates .......................................................... 573
The Standard Template Library.............................................................. 575
Summary ................................................................................................ 576
Q&A ...................................................................................................... 577
Quiz ....................................................................................................... 578
Exercises ................................................................................................. 578
20 Exceptions and Error Handling 581
Bugs, Errors, Mistakes, and Code Rot .................................................... 582
Exceptions ......................................................................................... 583
A Word About Code Rot ................................................................... 583
Preparing for Exceptions With C++........................................................ 584
How Exceptions Are Used ................................................................. 584
Using
try
Blocks and
catch
Blocks ........................................................ 589
Catching Exceptions .......................................................................... 590
More Than One

catch
Specification ................................................. 590
Exception Hierarchies ........................................................................ 593
Data in Exceptions and Naming Exception Objects ............................... 594
Exceptions and Templates ...................................................................... 600
Exceptions Without Errors ..................................................................... 603
Bugs and Debugging .............................................................................. 603
Breakpoints........................................................................................ 604
Watch Points ..................................................................................... 604
Examining Memory ........................................................................... 604
Assembler .......................................................................................... 605
Teach Yourself ANSI C++ in 21 Days
xx
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Summary ................................................................................................ 605
Q&A ...................................................................................................... 605
Quiz ....................................................................................................... 606
Exercises ................................................................................................. 607
21 Working With Multiple Files for Large Programs 609
Basic Concepts ....................................................................................... 610
Header Files....................................................................................... 610
Precompiled Header Files .................................................................. 612
Variable Names and Function Prototypes ............................................... 613
Implementation Files and Variable Scope ............................................... 613
Interdependency of Variables Between Files....................................... 615
More About
extern
................................................................................ 618
Hiding Variables and Global Scope Resolution ...................................... 618
Avoiding Multiple Declarations .............................................................. 620

Summary ................................................................................................ 621
Q&A ...................................................................................................... 621
Quiz ....................................................................................................... 622
Exercises ................................................................................................. 622
Week 3 In Review 625
Bonus Week At A Glance 635
Day 22 Advanced C++ Features 637
Namespaces and Class Libraries .............................................................. 638
Namespaces ....................................................................................... 638
Class Library Design .......................................................................... 640
How Polymorphism Works .................................................................... 643
Casting and Run-Time Type Identification ............................................ 644
Const
Cast ......................................................................................... 645
Dynamic Cast .................................................................................... 646
Static Cast.......................................................................................... 649
Reinterpret Cast................................................................................. 650
Type Info........................................................................................... 651
Explicit Constructors .............................................................................. 651
Data Alignment and Assembly Language ................................................ 652
Packing Data by Understanding Data Alignment .............................. 653
Spiking with Assembly Language ....................................................... 653
Summary ................................................................................................ 654
Q&A ...................................................................................................... 655
Quiz ....................................................................................................... 655
Exercises ................................................................................................. 656
23 More About Streams 659
The Streams Hierarchy ........................................................................... 659
Using
istrstream

................................................................................... 660
xxi
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Using
ostrstream
.............................................................................. 662
Stream Position ................................................................................. 663
Format Specification Flags ................................................................. 664
Creating Manipulators and Custom Stream Operators ...................... 664
Multiple Streams .................................................................................... 667
Summary ................................................................................................ 671
Q&A ...................................................................................................... 671
Quiz ....................................................................................................... 672
Exercises ................................................................................................. 672
24 Object-Oriented Design 673
What OOD Is Not ................................................................................. 673
Structured Programming ................................................................... 674
Structured Programming Drawbacks ................................................. 674
OOD Steps ............................................................................................ 675
Identify the Objects ........................................................................... 675
Identify the Methods ......................................................................... 676
Establish the Visibility ....................................................................... 677
Establish the Interface ........................................................................ 677
Implement the Objects ...................................................................... 678
Maintain or Iterate the Design ........................................................... 678
Other OOD Descriptions ...................................................................... 679
When Not to Use OOD ........................................................................ 679
Summary ................................................................................................ 680
Q&A ...................................................................................................... 681

Quiz ....................................................................................................... 681
Exercises ................................................................................................. 681
25 Data Structures 683
Looking Back at Arrays ........................................................................... 683
Queues and Stacks .................................................................................. 684
A Simple Queue Example .................................................................. 684
A Simple Stack Example .................................................................... 688
Trees ...................................................................................................... 689
Summary ................................................................................................ 698
Q&A ...................................................................................................... 698
Quiz ....................................................................................................... 699
Exercises ................................................................................................. 699
26 Simple Sorting and Searching 701
Sorting.................................................................................................... 702
The Bubble Sort ................................................................................ 703
The Selection Sort ............................................................................. 706
The Shell Sort .................................................................................... 707
The Quick Sort.................................................................................. 710
Sorting Disk Files .............................................................................. 712
Teach Yourself ANSI C++ in 21 Days
xxii
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Searching ................................................................................................ 712
The Straightforward String Search ..................................................... 712
The Binary Search ............................................................................. 714
Summary ................................................................................................ 717
Q&A ...................................................................................................... 717
Quiz ....................................................................................................... 718
Exercises ................................................................................................. 718
27 Common Mistakes and Basic Debugging 721

Class Explosion....................................................................................... 721
Boundary Violations and Off-by-One Errors .......................................... 725
Increment and Decrement Errors ........................................................... 726
Pointer Problems .................................................................................... 726
Bracket or Parenthesis Mismatch ............................................................ 727
Test and Assignment Confusion ............................................................. 728
Debugging Tips...................................................................................... 728
Asking for Help ...................................................................................... 729
Summary ................................................................................................ 729
Q&A ...................................................................................................... 730
Quiz ....................................................................................................... 730
Exercises ................................................................................................. 731
28 What’s Next? 733
The Standard Libraries ........................................................................... 734
String................................................................................................. 735
Localization Library ........................................................................... 735
Containers, Iterators, and Algorithms ................................................ 735
Bit Fields and Bitset ........................................................................... 736
Numerics Library............................................................................... 737
Next Steps .............................................................................................. 737
Sharpening Your Skills............................................................................ 737
Other Great Books ............................................................................ 737
Magazines .......................................................................................... 738
Internet and the World Wide Web .................................................... 738
Electronic Mail .................................................................................. 739
Summary ................................................................................................ 739
Q&A ...................................................................................................... 739
Quiz ....................................................................................................... 740
Appendixes
A Operator Precedence 741

B C++ Keywords 745
xxiii
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
C Binary and Hexadecimal 747
Other Bases ............................................................................................ 748
Around the Bases .................................................................................... 749
Binary ................................................................................................ 750
Why Base 2? ...................................................................................... 751
Bits, Bytes, and Nibbles ..................................................................... 751
Binary Numbers ................................................................................ 752
Hexadecimal ........................................................................................... 752
D Answers 757
Day 1 ..................................................................................................... 758
Quiz .................................................................................................. 758
Exercises ............................................................................................ 758
Day 2 ..................................................................................................... 758
Quiz .................................................................................................. 758
Exercises ............................................................................................ 759
Day 3 ..................................................................................................... 760
Quiz .................................................................................................. 760
Exercises ............................................................................................ 761
Day 4 ..................................................................................................... 761
Quiz .................................................................................................. 761
Exercises ............................................................................................ 762
Day 5 ..................................................................................................... 764
Quiz .................................................................................................. 764
Exercises ............................................................................................ 765
Day 6 ..................................................................................................... 767
Quiz .................................................................................................. 767

Exercises ............................................................................................ 768
Day 7 ..................................................................................................... 770
Quiz .................................................................................................. 770
Exercises ............................................................................................ 771
Day 8 ..................................................................................................... 772
Quiz .................................................................................................. 772
Exercises ............................................................................................ 773
Day 9 ..................................................................................................... 774
Quiz .................................................................................................. 774
Exercises ............................................................................................ 775
Day 10 ................................................................................................... 777
Quiz .................................................................................................. 777
Exercises ............................................................................................ 778
Day 11 ................................................................................................... 782
Quiz .................................................................................................. 782
Exercises ............................................................................................ 782
Day 12 ................................................................................................... 783
Quiz .................................................................................................. 783
Exercises ............................................................................................ 784
Teach Yourself ANSI C++ in 21 Days
xxiv
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Day 13 ................................................................................................... 785
Quiz .................................................................................................. 785
Exercises ............................................................................................ 786
Day 14 ................................................................................................... 787
Quiz .................................................................................................. 787
Exercises ............................................................................................ 788
Day 15 ................................................................................................... 793
Quiz .................................................................................................. 793

Exercises ............................................................................................ 794
Day 16 ................................................................................................... 798
Quiz .................................................................................................. 798
Exercises ............................................................................................ 799
Day 17 ................................................................................................... 800
Quiz .................................................................................................. 800
Exercises ............................................................................................ 801
Day 18 ................................................................................................... 803
Quiz .................................................................................................. 803
Exercises ............................................................................................ 804
Day 19 ................................................................................................... 805
Quiz .................................................................................................. 805
Exercises ............................................................................................ 806
Day 20 ................................................................................................... 810
Quiz .................................................................................................. 810
Exercises ............................................................................................ 811
Day 21 ................................................................................................... 816
Quiz .................................................................................................. 816
Exercises ............................................................................................ 816
Day 22 ................................................................................................... 818
Quiz .................................................................................................. 818
Exercises ............................................................................................ 819
Day 23 ................................................................................................... 821
Quiz .................................................................................................. 821
Exercises ............................................................................................ 822
Day 24 ................................................................................................... 823
Quiz .................................................................................................. 823
Exercises ............................................................................................ 823
Day 25 ................................................................................................... 824
Quiz .................................................................................................. 824

Exercises ............................................................................................ 824
Day 26 ................................................................................................... 826
Quiz .................................................................................................. 826
Exercises ............................................................................................ 827
Day 27 ................................................................................................... 828
Quiz .................................................................................................. 828
Exercises ............................................................................................ 829
Day 28 ................................................................................................... 830
Quiz .................................................................................................. 830
Index 831
xxv
Contents
P2/V3/sqc5 TY ANSI C++ in 21 30887-6 Casey 2.23.96 FM LP#3
Acknowledgments
I would like to acknowledge the many people who contributed to this book, both directly and
indirectly. First and foremost, Stacey and Robin Liberty, whose support, encouragement,
and patience made it possible. Also, Mike Kraley, Ed Belove, and Patrick Johnson, who create
an intellectual atmosphere at the Interchange Online Network, which makes it a gas to come
to work every day, and the many, many developers at Ziff from whom I learned whatever it
is I know about C++.
I must particularly acknowledge those who taught me how to program, Skip Gilbrech and
David McCune, and those who taught me C++, including Steve Rogers and especially Steven
Zagieboylo. Others who contributed directly or indirectly to this book include Scott Boag,
David Bogartz, Gene Broadway, Drew and Al Carlson, Frank Childs, Jim Culbert, Fran
Daniels, Thomas Dobbing, James Efstratiou, June Goldstein, Basha Goldstein-Weiss,
Michael Griffin, David Heath, Eric Helliwell, Gisele and Ed Herlihy, Mushtaq Khalique,
Matt Kingman, Steve Leland, Sangam Pant, Mike Rothman, Michael Smith, Frank Tino,
Seth Weiss, Donovan White, Mark Woodbury, and Alan Zeitchek. Special thanks go to
Wayne Wylupski and Steven Zagieboylo.
Programming is as much a business and creative experience as it is a technical one, and I must

therefore acknowledge Tom Hottenstein, Jay Leve, David Rollert, David Shnaider, and
Robert Spielvogel. I also want to thank the many people at Sams Publishing who worked
so hard to create this book. If any of what I’ve written is especially clear, it is thanks to the
editors.
Finally, I’d like to thank Mrs. Kalish, who taught my sixth-grade class how to do binary
arithmetic in 1965, when neither she nor we knew why.
—Jesse Liberty
The first people that come to mind are my family. They’ve been there through thick and thin,
shared my enthusiasm and bore the brunt of my frustrations. Praise God for their love and
devotion.
Maggie, if I had to do it all again, I’d still say “I do.” Timmy, you’re everything I could
ever want for a son; I’m very proud. Heather, thank you for your kindness and gentle spirit,
and for always loving Daddy even when he was cranky. Alicia, though you are small, your
love has always been big; you have been a wonderful daughter. Amber, thank you for your
gift of joy and fun that helped me keep focus on the things that really matter.
—J. Mark Hord

×