C++ without fear: a beginner's guide that makes you feel smart 0321246950, 9780321246950

If you've always wanted to learn how to program a computer, or to learn the widely used C++ programming language in

197 95 3MB

English Pages xxv, 486 pages: illustrations; 24 cm + 1 CD-ROM (4 3/4 in) [518] Year 2004;2005

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover......Page 1
Contents......Page 8
Why a New C++ Book?......Page 20
Multiple Learning Paths: What Fits You Best......Page 21
What Is Not Covered?......Page 22
Why Should Anyone Start with C++?......Page 23
Tips and Tricks: What Do I Watch Out For?......Page 24
Acknowledgments......Page 26
Computers Do Only What You Tell Them......Page 30
Write the Equivalent C++ Statements......Page 31
Some Nerdy Definitions—A Review......Page 33
What’s Different about C++?......Page 35
Interlude: What about Java and C#?......Page 36
Enter the Program Statements......Page 37
Build the Program (Compile and Link)......Page 38
Revise As Needed......Page 39
Installing Your Own C++ Compiler......Page 40
If You’re Using the RHIDE Environment......Page 41
If You’re Using Microsoft Visual Studio......Page 42
How It Works......Page 43
Interlude: What about #include and “using”?......Page 45
Advancing to the Next Print Line......Page 46
How It Works......Page 47
Exercises......Page 48
Storing Data: C++ Variables......Page 49
Introduction to Data Types......Page 50
Example 1.3. Convert Temperatures......Page 52
How It Works......Page 54
Variations on the Example......Page 56
A Word about Variable Names and Keywords......Page 58
Chapter 1 Summary......Page 59
But First, a Few Words about Data Types......Page 62
Interlude: For C Programmers......Page 65
If and if-else......Page 66
Interlude: Why Two Operators (= and ==)?......Page 69
Example 2.1. Odd or Even?......Page 70
How It Works......Page 71
Optimizing the Code......Page 72
Introducing Loops......Page 73
Example 2.2. Print 1 to N......Page 77
How It Works......Page 78
True and False in C++......Page 79
The Increment Operator (++)......Page 80
Statements vs. Expressions......Page 82
Introducing Boolean (Short-Circuit) Logic......Page 83
Interlude: What Is “true”?......Page 84
Example 2.3. Testing a Person’s Age......Page 85
Introducing the Math Library......Page 86
Example 2.4. Prime-Number Test......Page 87
How It Works......Page 89
Chapter 2 Summary......Page 90
Loops Used for Counting......Page 94
Introducing the “for” Loop......Page 95
A Wealth of Examples......Page 97
Interlude: Does “for” Always Behave like “while”?......Page 98
How It Works......Page 99
Statement Blocks with “for”......Page 100
Declaring Loop Variables on the Fly......Page 101
Example 3.2. Prime-Number Test with “for”......Page 102
How It Works......Page 103
Exercise......Page 105
Comparative Languages 101: The Basic “for” Statement......Page 106
Chapter 3 Summary......Page 107
The Concept of Function......Page 110
Function Calls and the Flow of the Program......Page 112
The Basics of Using Functions......Page 113
Step One: Declare (Prototype) the Function......Page 114
Step Two: Define the Function......Page 115
Step Three: Call the Function......Page 116
Example 4.1. Triangle-Number Function......Page 117
How It Works......Page 118
Optimizing the Program......Page 119
Example 4.2. Prime-Number Function......Page 121
How It Works......Page 122
Local and Global Variables......Page 124
Recursive Functions......Page 126
Example 4.3. Greatest Common Factor (GCF)......Page 127
How It Works......Page 129
Exercises......Page 130
Example 4.4. Prime Factorization......Page 131
How It Works......Page 132
Interlude: For Math Junkies......Page 134
Example 4.5. Random-Number Generator......Page 135
How It Works......Page 137
Chapter 4 Summary......Page 138
A First Look at C++ Arrays......Page 140
Initializing Arrays......Page 142
Interlude: Why Use Zero-Based Indexes?......Page 143
Example 5.1. Print Out Elements......Page 144
How It Works......Page 145
Example 5.2. How Random Is Random?......Page 146
How It Works......Page 149
Strings and Arrays of Strings......Page 151
Example 5.3. Card Dealer #1......Page 152
How It Works......Page 154
Example 5.4. Card Dealer #2......Page 155
How It Works......Page 157
Example 5.5. Card Dealer #3......Page 159
How It Works......Page 161
Optimizing the Program......Page 163
A Word to the Wise......Page 164
2-D Arrays: Into the Matrix......Page 165
Chapter 5 Summary......Page 166
The Concept of Pointer......Page 168
Interlude: What Do Addresses Really Look Like?......Page 169
Declaring and Using Pointers......Page 171
How It Works......Page 174
Swap: Another Function Using Pointers......Page 176
Example 6.2. Array Sorter......Page 178
How It Works......Page 181
Exercises......Page 182
Pointer Arithmetic......Page 183
Pointers and Array Processing......Page 185
Example 6.3. Zero Out an Array......Page 186
How It Works......Page 187
Optimizing the Program......Page 188
Exercises......Page 189
Chapter 6 Summary......Page 190
Text Storage on the Computer......Page 192
Interlude: How Does the Computer Translate Programs?......Page 193
It Don’t Mean a Thing If It Ain’t Got That String......Page 194
String-Manipulation Functions......Page 195
Example 7.1. Building Strings......Page 197
How It Works......Page 199
Exercises......Page 200
Reading String Input......Page 201
Example 7.2. Get a Number......Page 204
How It Works......Page 205
Example 7.3. Convert to Uppercase......Page 206
How It Works......Page 207
Exercises......Page 208
Individual Characters vs. Strings......Page 209
Example 7.4. Analyze Input......Page 210
How It Works......Page 212
Exercises......Page 214
The New C++ String Class......Page 215
Declare and Initialize Variables of Type string......Page 216
Working with Variables of Type string......Page 217
Example 7.5. Building Strings with the string Type......Page 218
How It Works......Page 219
Other Operations on the string Type......Page 220
Chapter 7 Summary......Page 222
Introducing File-Stream Objects......Page 226
How to Refer to Disk Files......Page 228
Example 8.1. Write Text to a File......Page 229
How It Works......Page 230
Exercises......Page 231
Example 8.2. Display a Text File......Page 232
How It Works......Page 233
Exercises......Page 234
Text Files vs.“Binary” Files......Page 235
Introducing Binary Operations......Page 237
Example 8.3. Random-Access Write......Page 240
How It Works......Page 242
Example 8.4. Random-Access Read......Page 243
Exercises......Page 245
Chapter 8 Summary......Page 246
Command-Line Arguments......Page 248
Example 9.1. Display File from Command Line......Page 250
Exercises......Page 252
Function Overloading......Page 253
Interlude: Overloading and OOPS......Page 254
Example 9.2. Printing Different Types of Arrays......Page 255
How It Works......Page 256
The do-while Loop......Page 257
The switch-case Statement......Page 259
Multiple Modules......Page 260
Say Hello to Exceptions......Page 263
Handling Exceptions: A First Attempt......Page 264
Introducing try-catch Exception Handling......Page 265
Example 9.3. Exception Handling with GCF......Page 268
How It Works......Page 269
Interlude: Can I Use Multiple try-catch Blocks?......Page 270
Chapter 9 Summary......Page 271
Why Get Object Oriented?......Page 274
A String Parser......Page 276
Objects vs. Classes......Page 277
Another Example: The Fraction Class......Page 278
Object Creation and Destruction......Page 279
Inheritance, or Subclassing......Page 280
Creating Shared Interfaces......Page 281
Polymorphism: True Object Independence......Page 282
Polymorphism and Virtual Functions......Page 284
Interlude: Polymorphism and Traditional Languages......Page 285
What about Reusability?......Page 286
Chapter 10 Summary......Page 288
Point: A Simple Class......Page 290
Private: Members Only (Protecting the Data)......Page 292
Example 11.1. Testing the Point Class......Page 295
How It Works......Page 296
Introducing the Fraction Class......Page 297
Inline Functions......Page 300
Find the Greatest Common Factor......Page 302
Find the Lowest Common Multiple......Page 304
Example 11.2. Fraction Support Functions......Page 305
How It Works......Page 307
Exercises......Page 308
Example 11.3. Testing the Fraction Class......Page 309
How It Works......Page 311
Example 11.4. Fraction Arithmetic: add and mult......Page 312
How It Works......Page 316
Chapter 11 Summary......Page 317
Introducing Constructors......Page 320
Multiple Constructors (Overloading)......Page 322
The Default Constructor… and a Warning......Page 323
Interlude: Is C++ Out to Trick You with the Default Constructor?......Page 324
Example 12.1. Point Class Constructors......Page 325
Exercises......Page 327
Example 12.2. Fraction Class Constructors......Page 328
How It Works......Page 330
Reference Variables and Arguments (&)......Page 331
The Copy Constructor......Page 333
Interlude: The Copy Constructor and References......Page 334
Example 12.3. Fraction Class Copy Constructor......Page 335
How It Works......Page 338
Chapter 12 Summary......Page 339
Introducing Class Operator Functions......Page 342
Operator Functions As Global Functions......Page 345
Improve Efficiency with References......Page 347
Example 13.1. Point Class Operators......Page 349
How It Works......Page 351
Example 13.2. Fraction Class Operators......Page 352
How It Works......Page 355
Working with Other Types......Page 357
The Class Assignment Function (=)......Page 358
The Test-for-Equality Function (==)......Page 359
Interlude: What about the Boolean Type (bool)?......Page 360
A Class "Print" Function......Page 361
Example 13.3. The Completed Fraction Class......Page 362
How It Works......Page 366
Exercises......Page 367
Chapter 13 Summary......Page 368
The "new" Operator......Page 372
Objects and "new"......Page 374
Allocating Array Data......Page 376
Interlude: Dealing with Problems in Memory Allocation......Page 377
Example 14.1. Dynamic Memory in Action......Page 378
Design for a Parser (Lexical Analyzer)......Page 379
Example 14.2. The StringParser Class......Page 384
How It Works......Page 387
Exercises......Page 389
Chapter 14 Summary......Page 390
Introducing the String Class......Page 392
Introducing Class Destructors......Page 393
Example 15.1. A Simple String Class......Page 395
How It Works......Page 396
"Deep" Copying and the Copy Constructor......Page 399
The "this" Keyword......Page 401
Revisiting the Assignment Operator......Page 403
Writing a Concatenation Function......Page 404
Example 15.2. The Complete String Class......Page 406
How It Works......Page 409
Exercises......Page 410
Chapter 15 Summary......Page 411
Subclassing for Fun and Profit......Page 414
Interlude: Why "public" Base Classes?......Page 417
Example 16.1. The FloatFraction Class......Page 418
How It Works......Page 422
Problems with the FloatFraction Class......Page 423
Add the Missing Constructors......Page 425
Resolving Type Conflicts with the Base Class......Page 426
Example 16.2. The Completed FloatFraction Class......Page 427
Example 16.3. The ProperFraction Class......Page 428
How It Works......Page 431
Private and Protected Members......Page 433
Example 16.4. Contained Members: FractionUnits......Page 435
How It Works......Page 437
Chapter 16 Summary......Page 439
A Different Approach to the FloatFraction Class......Page 442
Virtual Functions to the Rescue!......Page 444
Interlude: What Is the Virtual Penalty?......Page 445
Example 17.1. The Revised FloatFraction Class......Page 447
How It Works......Page 449
Improving the Code......Page 450
"Pure Virtual" and Other Arcane Matters......Page 452
Abstract Classes and Interfaces......Page 453
Why cout Is Not Truly Polymorphic......Page 455
Example 17.2. True Polymorphism: The Printable Class......Page 456
How It Works......Page 458
A Final Word (or Two)......Page 460
A Final Final Word......Page 461
Chapter 17 Summary......Page 462
Appendix A: C++ Operators......Page 464
Appendix B: Intrinsic Data Types......Page 468
Basic Expression Syntax......Page 470
Basic Statement Syntax......Page 471
Control Structures......Page 472
Special Control Statements......Page 474
Data Declarations......Page 475
Function Declarations......Page 476
Class Declarations......Page 477
Appendix D: ASCII Codes......Page 480
String Functions......Page 482
Data-Conversion Functions......Page 483
Math Functions......Page 484
Randomization......Page 486
A......Page 488
C......Page 489
E......Page 490
G......Page 491
I......Page 492
O......Page 493
P......Page 494
V......Page 495
Index......Page 498
A......Page 499
C......Page 500
D......Page 503
F......Page 504
I......Page 507
L......Page 508
O......Page 509
P......Page 510
R......Page 511
S......Page 512
T......Page 514
Z......Page 515
Recommend Papers

C++ without fear: a beginner's guide that makes you feel smart
 0321246950, 9780321246950

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

C++ Without Fear

This page intentionally left blank

C++ Without Fear A Beginner’s Guide That Makes You Feel Smart

Brian Overland

Prentice Hall Professional Technical Reference Upper Saddle River, New Jersey 07458 www.phptr.com

Library of Congress Cataloging-in-Publication Data is on file at the Library of Congress © 2005 Pearson Education, Inc. Publishing as Prentice Hall Professional Technical Reference Upper Saddle River, New Jersey 07458 Prentice Hall PTR offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact: U.S. Corporate and Government Sales, 1-800-382-3419, [email protected]. For sales outside of the U.S., please contact: International Sales, [email protected]. Company and product names mentioned herein are trademarks or registered trademarks of their respective owners. All rights reserved. No part of this book may be reproduced, in any form or by any means, without permission in writing from the publisher. Text printed in the United States on recycled paper at Courier Stoughton in Stoughton, Massachusetts.

7th Printing December 2007 ISBN 0-321-24695-0 Pearson Education Ltd. Pearson Education Australia Pty., Limited Pearson Education South Asia Pte. Ltd. Pearson Education Asia Ltd. Pearson Education Canada, Ltd. Pearson Educación de Mexico, S.A. de C.V. Pearson Education—Japan Pearson Malaysia S.D.N. B.H.D.

To all the great teachers I have known, and to Fara and Skyler, who will not be forgotten

This page intentionally left blank

Contents Preface Why a New C++ Book? What Else Is New about This Book? Multiple Learning Paths: What Fits You Best What If You Already Have a Programming Background? What Is Not Covered? Why Should Anyone Start with C++? To Get Started . . . Tips and Tricks: What Do I Watch Out For?

Acknowledgments Chapter 1

Your First C++ Programs Thinking like a Programmer Computers Do Only What You Tell Them Determine What the Program Will Do Write the Equivalent C++ Statements Some Nerdy Definitions—A Review What’s Different about C++? Interlude What about Java and C#? Building a C++ Program Enter the Program Statements Build the Program (Compile and Link) Test the Program Revise As Needed Installing Your Own C++ Compiler

xix xix xx xx xxi xxi xxii xxiii xxiii xxv

1 1 1 2 2 4 6 7 8 8 9 10 10 11

vii

viii

Chapter 2

Contents

Example 1.1. Print a Message If You’re Using the RHIDE Environment If You’re Using Microsoft Visual Studio How It Works Exercises Interlude What about #include and “using”? Advancing to the Next Print Line Example 1.2. Print Multiple Lines How It Works Exercises Interlude What Is a String? Storing Data: C++ Variables Introduction to Data Types Interlude Why Double Precision, Not Single? Example 1.3. Convert Temperatures How It Works Variations on the Example Exercises A Word about Variable Names and Keywords Exercise Chapter 1 Summary

12 12 13 14 16 16 17 18 18 19 20 20 21 23 23 25 27 29 29 30 30

Decisions, Decisions

33

But First, a Few Words about Data Types Interlude For C Programmers Decision Making in Programs If and if-else Interlude Why Two Operators (= and ==)? Example 2.1. Odd or Even? How It Works Optimizing the Code Exercise Introducing Loops Interlude Infinite Loopiness Example 2.2. Print 1 to N How It Works Exercises

33 36 37 37 40 41 42 43 44 44 48 48 49 50

Contents

Chapter 3

Chapter 4

ix

True and False in C++ Interlude The bool Data Type The Increment Operator (++) Statements vs. Expressions Introducing Boolean (Short-Circuit) Logic Interlude What Is “true”? Example 2.3. Testing a Person’s Age How It Works Exercise Introducing the Math Library Example 2.4. Prime-Number Test How It Works Optimizing the Program Exercise Chapter 2 Summary

50 51 51 53 54 55 56 57 57 57 58 60 61 61 61

The Handy, All-Purpose “for” Statement

65

Loops Used for Counting Introducing the “for” Loop A Wealth of Examples Interlude Does “for” Always Behave like “while”? Example 3.1. Printing 1 to N with “for” How It Works Exercises Statement Blocks with “for” Declaring Loop Variables on the Fly Example 3.2. Prime-Number Test with “for” How It Works Exercise Comparative Languages 101: The Basic “for” Statement Chapter 3 Summary

65 66 68 69 70 70 71 71 72 73 74 76 77 78

Functions: Many Are Called

81

The Concept of Function Function Calls and the Flow of the Program

81 83

x

Chapter 5

Contents

The Basics of Using Functions Step One: Declare (Prototype) the Function Step Two: Define the Function Step Three: Call the Function Example 4.1. Triangle-Number Function How It Works Optimizing the Program Exercises Example 4.2. Prime-Number Function How It Works Exercises Local and Global Variables Recursive Functions Example 4.3. Greatest Common Factor (GCF) How It Works Exercises Example 4.4. Prime Factorization How It Works Interlude For Math Junkies Exercises Example 4.5. Random-Number Generator How It Works Exercise Chapter 4 Summary

84 85 86 87 88 89 90 92 92 93 95 95 97 98 100 101 102 103 105 106 106 108 109 109

Arrays: We’ve Got Their Number

111

A First Look at C++ Arrays Initializing Arrays Zero-Based Indexing Interlude Why Use Zero-Based Indexes? Example 5.1. Print Out Elements How It Works Exercises Example 5.2. How Random Is Random? How It Works Exercises Strings and Arrays of Strings

111 113 114 114 115 116 117 117 120 122 122

Contents

Chapter 6

Chapter 7

xi

Example 5.3. Card Dealer #1 How It Works Exercise Example 5.4. Card Dealer #2 How It Works Exercise Example 5.5. Card Dealer #3 How It Works Optimizing the Program Exercise A Word to the Wise 2-D Arrays: Into the Matrix Chapter 5 Summary

123 125 126 126 128 130 130 132 134 135 135 136 137

Pointers: Getting a Handle on Data

139

The Concept of Pointer Interlude What Do Addresses Really Look Like? Declaring and Using Pointers Example 6.1. The Double-It Function How It Works Exercises Swap: Another Function Using Pointers Example 6.2. Array Sorter How It Works Exercises Pointer Arithmetic Pointers and Array Processing Example 6.3. Zero Out an Array How It Works Optimizing the Program Exercises Chapter 6 Summary

139 140 142 145 145 147 147 149 152 153 154 156 157 158 159 160 161

Strings: Analyzing the Text

163

Text Storage on the Computer Interlude How Does the Computer Translate Programs? It Don’t Mean a Thing If It Ain’t Got That String

163 164 165

xii

Chapter 8

Contents

String-Manipulation Functions Example 7.1. Building Strings How It Works Exercises Interlude What about Escape Sequences? Reading String Input Example 7.2. Get a Number How It Works Exercise Example 7.3. Convert to Uppercase How It Works Exercises Individual Characters vs. Strings Example 7.4. Analyze Input How It Works Exercises The New C++ String Class Include String-Class Support Declare and Initialize Variables of Type string Working with Variables of Type string Input and Output Example 7.5. Building Strings with the string Type How It Works Exercises Other Operations on the string Type Chapter 7 Summary

166 168 170 171 172 172 175 176 177 177 178 179 180 181 183 185 186 187 187 188 189 189 190 191 191 193

Files: Electronic Storage

197

Introducing File-Stream Objects How to Refer to Disk Files Example 8.1. Write Text to a File How It Works Exercises Example 8.2. Display a Text File How It Works Exercises Text Files vs. “Binary” Files Interlude Are “Binary Files” Really More Binary?

197 199 200 201 202 203 204 205 206 208

Contents

Chapter 9

Chapter 10

xiii

Introducing Binary Operations Example 8.3. Random-Access Write How It Works Exercises Example 8.4. Random-Access Read How It Works Exercises Chapter 8 Summary

208 211 213 214 214 216 216 217

Some Advanced Programming Techniques

219

Command-Line Arguments Example 9.1. Display File from Command Line How It Works Exercises Function Overloading Interlude Overloading and OOPS Example 9.2. Printing Different Types of Arrays How It Works Exercise The do-while Loop The switch-case Statement Multiple Modules Exception Handling Say Hello to Exceptions Handling Exceptions: A First Attempt Introducing try-catch Exception Handling Example 9.3. Exception Handling with GCF How It Works Exercise Interlude Can I Use Multiple try-catch Blocks? Chapter 9 Summary

219 221 223 223 224 225 226 227 228 228 230 231 234 234 235 236 239 240 241 241 242

Getting Yourself Object Oriented

245

Why Get Object Oriented? A String Parser Objects vs. Classes

245 247 248

xiv

Chapter 11

Chapter 12

Contents

Another Example: The Fraction Class Object Creation and Destruction Inheritance, or Subclassing Creating Shared Interfaces Polymorphism: True Object Independence Polymorphism and Virtual Functions Interlude Polymorphism and Traditional Languages What about Reusability? Chapter 10 Summary

249 250 251 252 253 255 256 257 259

The Fraction Class

261

Point: A Simple Class Interlude For C Programmers: Structures and Classes Private: Members Only (Protecting the Data) Example 11.1. Testing the Point Class How It Works Exercises Introducing the Fraction Class Inline Functions Find the Greatest Common Factor Find the Lowest Common Multiple Example 11.2. Fraction Support Functions How It Works Exercises Example 11.3. Testing the Fraction Class How It Works Exercise Interlude A New Kind of #include? Example 11.4. Fraction Arithmetic: add and mult How It Works Exercises Chapter 11 Summary

261 263 263 266 267 268 268 271 273 275 276 278 279 280 282 283 283 283 287 288 288

Constructors: If You Build It . . .

291

Introducing Constructors Multiple Constructors (Overloading)

291 293

Contents

Chapter 13

xv

The Default Constructor… and a Warning Interlude Is C++ Out to Trick You with the Default Constructor? Example 12.1. Point Class Constructors How It Works Exercises Example 12.2. Fraction Class Constructors How It Works Exercises Reference Variables and Arguments (&) The Copy Constructor Interlude The Copy Constructor and References Example 12.3. Fraction Class Copy Constructor How It Works Exercises Chapter 12 Summary

294 295 296 298 298 299 301 302 302 304 305 306 309 310 310

Operator Functions: Doing It with Class

313

Introducing Class Operator Functions Operator Functions As Global Functions Improve Efficiency with References Example 13.1. Point Class Operators How It Works Exercises Example 13.2. Fraction Class Operators How It Works Exercises Working with Other Types The Class Assignment Function (=) The Test-for-Equality Function (==) Interlude What about the Boolean Type (bool)? A Class “Print” Function Example 13.3. The Completed Fraction Class How It Works Exercises Chapter 13 Summary

313 316 318 320 322 323 323 326 328 328 329 330 331 332 333 337 338 339

xvi

Contents

Chapter 14

What’s “new”: The StringParser Class

343

The “new” Operator Objects and “new” Allocating Array Data Interlude Dealing with Problems in Memory Allocation Example 14.1. Dynamic Memory in Action How It Works Exercise Design for a Parser (Lexical Analyzer) Example 14.2. The StringParser Class How It Works Improving the Code Exercises Chapter 14 Summary

343 345 347 348 349 350 350 350 355 358 360 360 361

What’s “this”: The String Class

363

Introducing the String Class Introducing Class Destructors Example 15.1. A Simple String Class How It Works Exercises “Deep” Copying and the Copy Constructor The “this” Keyword Revisiting the Assignment Operator Writing a Concatenation Function Example 15.2. The Complete String Class How It Works Exercises Chapter 15 Summary

363 364 366 367 370 370 372 374 375 377 380 381 382

Inheritance: What a Legacy

385

Subclassing for Fun and Profit Interlude Why “public” Base Classes? Example 16.1. The FloatFraction Class How It Works Exercises

385 388 389 393 394

Chapter 15

Chapter 16

Contents

Chapter 17

xvii

Problems with the FloatFraction Class Default Constructors for Subclasses Copy Constructors for Subclasses Assignment Function for Subclasses Add the Missing Constructors Resolving Type Conflicts with the Base Class Example 16.2. The Completed FloatFraction Class How It Works Exercises Example 16.3. The ProperFraction Class How It Works Exercises Private and Protected Members Example 16.4. Contained Members: FractionUnits How It Works Exercise Chapter 16 Summary

394 396 396 396 396 397 398 399 399 399 402 404 404 406 408 410 410

Polymorphism: Object Independence

413

A Different Approach to the FloatFraction Class Virtual Functions to the Rescue! Interlude What Is the Virtual Penalty? Example 17.1. The Revised FloatFraction Class How It Works Improving the Code Exercise “Pure Virtual” and Other Arcane Matters Abstract Classes and Interfaces Why cout Is Not Truly Polymorphic Example 17.2. True Polymorphism: The Printable Class How It Works Exercise A Final Word (or Two) A Final Final Word Chapter 17 Summary

413 415 416 418 420 421 423 423 424 426 427 429 431 431 432 433

xviii

Contents

Appendix A

C++ Operators

435

Appendix B

Intrinsic Data Types

439

Appendix C

C++ Syntax Summary

441

Literal Constants Basic Expression Syntax Basic Statement Syntax Control Structures Special Control Statements Data Declarations Function Declarations Class Declarations

441 441 442 443 445 446 447 448

Appendix D

ASCII Codes

451

Appendix E

Common Library Functions

453

String Functions Data-Conversion Functions Single-Character Functions Math Functions Randomization

453 454 455 455 457

Glossary of Terms

459

Index

469

Appendix F

Preface In my ten years at Microsoft, I found the top-level programmers (“software development engineers,” we called them) to be an interesting breed. Once you got them to open up and talk about their projects, they could be an articulate and passionate group. The trick was to get beyond the initial barrier, to convince them that you spoke their language. Experienced programmers sometimes divide the world into two groups: those who are “technical” and those who are not. At times a yawning gap seems to exist between them, like that between people with perfect pitch and those without. For programmers, the dividing line these days is most often the ability to program in C++. This attitude stems from the perception of C++ as difficult to learn. This book is dedicated to the idea that C++ need not be difficult. It’s often a more challenging language than Basic, to be sure, but with the right kind of help, you can master the tricks of C++.

Why a New C++ Book? Introductory programming books for C++ exist aplenty. But many—probably the great majority—are “introductory” only in the sense that they don’t assume knowledge of C++ specifically. They usually assume that you’ve programmed in another language before, preferably in several. This book does not make that assumption. All that’s required is that you’re comfortable with a computer and that you’ve run applications such as a word processor or e-mail reader. Once you narrow the available C++ texts down to those that require no programming experience at all, there’s a much smaller group of books from which to choose.

xix

xx

Preface

What Else Is New about This Book? The book you hold in your hand stresses the fundamentals of programming. Yet even if you have programmed before (maybe you’ve taken a basic course in high school or college), you may find this a useful review. This book delves into the topic of how to think like a programmer . . . and why specific language features matter. The why is as important as the how. People learn best when they get the benefit of several learning methods reinforcing one another. Therefore, every topic in this book is introduced by a general discussion with short program-code examples, accompanied by the following: ◗ A complete program example. Usually I provide a complete example that can be run and tested. The emphasis in this book is on short examples that do something interesting and useful and, when possible, something fun. ◗ Programming exercises. Each example has a series of accompanying exercises, in which I encourage you to modify the example or write similar programs, so that from the beginning you’re writing C++ code. Answers to these exercises provided on the accompanying CD in the folder “Example Code and Answers to Exercises.” ◗ Generous use of illustrations. Many so-called beginning texts don’t use this approach at all. But I often find that the right figures can clarify an abstract concept. One picture is worth a thousand lectures, sometimes. ◗ A special “How It Works” section for every major example in the book. How-toprogram texts are notorious for giving you a long example followed by a couple of paragraphs of text. That’s not the approach of this book. Complete examples are listed so that you can see everything in context. But after each example, I go back and dissect the program a couple of lines at a time, explaining how and why each bit of the program does what it does.

Multiple Learning Paths: What Fits You Best In addition to the multiple learning techniques just described, this book contains frequent Interludes, where the more curious reader will find additional background and explanations why C++ features work the way they do. If you’re eager to just get C++ programs working, you may want to skip the Interludes and return to them later. One of the advantages of this book is that it accommodates multiple learning paths.

Preface

xxi

Unlike some texts, this book does not start with an exhaustive description of all language features such as data types, control structures, and operators. That would be like learning French by spending months memorizing nouns rather than learning to speak a complete sentence. This book focuses on getting real programs to work, right away. At the same time, it’s helpful to have access to a thorough-but-concise summary of language features. This book provides that summary in a series of convenient appendixes.

What If You Already Have a Programming Background? If you already know another programming language but are new to C++, that’s not a problem. Certain ideas in programming never get old: what it means to think like a programmer, what’s going on just beneath the surface, why the language is constructed the way it is. This review of programming fundamentals may be of interest anyway. But if not, you can speed through the first chapter or two. C++ gets challenging quickly enough.

What Is Not Covered? The goal of this book is to make you comfortable and conversant in C++, including objected-oriented programming features (classes and objects) that, although a relatively advanced topic, are at the heart of C++. The goal is not to teach every last bit of language syntax or to describe how every statement is translated into machine behavior (that is, how it is implemented), although in some places I do discuss that. In my view, the good majority of beginning texts make the mistake of trying to cover every obscure corner of the language, even though there is ample room in intermediate to advanced books to handle those topics. In case you are a C++ expert or otherwise a guru perusing this book, or you have some familiarity with the scope of the language, here is a summary of what’s in C++ but is not covered in this book. (Consider this a “truth in advertising” disclaimer.) ◗ Bit fields and bit operations. Bit operations can occasionally be useful for programs that must make extreme use of compact space, but in general, bit operations are rarely necessary. This is a good advanced topic. Likewise, I don’t cover the union keyword (another feature used for compaction).

xxii

Preface

◗ Windows and GUI programming. These are difficult subjects, deserving of their own book (or three). Visual C++ requires understanding of a complex architecture and thorough knowledge of object-oriented programming systems (OOPS). Reading this book first will give you a background in OOPS. ◗ Templates and STL (Standard Template Library). This is another good topic for an advanced book. A template is a way of creating a generalized data structure in which an abstract mechanism can be combined with any number of specific data types. The template-defining capability was not originally in the C++ specification, although it is now standard. Although this book does cover exception handling—a way to respond to runtime errors—I don’t stress it, because it is most appropriate in complex programs and not likely to be as useful to a beginner.

Why Should Anyone Start with C++? Some people will tell you that C++ is unsuitable for beginners; therefore, unless you’re in the elite of talented and experienced programmers, you shouldn’t bother. I don’t agree with that. There are some good reasons for learning C++ early in your programming career. People used to spend a lot of time mastering the C language first. Yet C is rarely used for real work anymore. Now students learn it primarily as a steppingstone to C++. But this makes little sense. You can pick up some bad habits learning C. It’s better to go directly to C++. C++ is now the language of choice for systems programmers as well as for writing commercial software—including games, graphics, and business-oriented programs. Some other languages (notably Microsoft’s Visual Basic) are more forgiving. But as with C, Basic can encourage bad habits. C++ offers any learner some unique rewards. ◗ Like the C language, C++ is a systems-programming language. In learning about C++ (at least in this book) you’ll learn a lot about how things work in the computer and why they do. ◗ Unlike C, C++ is a good implementation of object-oriented programming. This is an approach to programming in which you create intelligent data structures, especially well suited to things such as graphics programming. Object-oriented programming also lets you define new types that in effect expand the capabilities of the language itself. In learning object-oriented programming, you’ll learn more about the current state of software design and where it’s going.

Preface

xxiii

The first half of this book focuses on the fundamentals of C++: how to get a program to work and accomplish basic tasks. From the beginning, however, it does get you to start using and understanding objects. The second half focuses more completely on object-oriented programming, with special emphasis on how you can use it to write useful—and reusable— program code.

To Get Started . . . This book provides an added bonus: an accompanying CD with a free compiler, which is the language translator needed to write and execute programs in C++. All the programming examples in this book have been tested and retested with this compiler. The examples also work with compilers such as C++ in Microsoft Visual Studio.NET, although you’ll need to follow the special instructions in Chapter 1 for use with that environment. To install the free C++ compiler, just insert the CD into a PC and follow the instructions in the README.TXT file in the root directory. This compiler is a free shareware version of GNU C++. You are free to use it to build and distribute your own programs. It also comes with a free development environment, so (as described in Chapter 1), you can write programs and then build them (translate them into executable form) at the touch of a single keystroke.

Tips and Tricks: What Do I Watch Out For? Perhaps what gives C-based languages their reputation for being more difficult than some others is that they have some “gotchas”—things that will catch you off guard if you don’t have a friendly mentor standing next to you to steer you around the pitfalls. As much as anything, this book is about keeping you safe from the gotchas. For too many people, the ability to program is gained only after making the same unnecessary mistakes over and over. Above all, I hope to communicate some of what makes the subject, at least at times, so interesting. Software development can test your patience as you track down elusive bugs. But the concepts can be fascinating. In our new century, programming computers has become the new kind of craftsmanship, the new mode of fashioning fine tools, for a world that runs on information.

This page intentionally left blank

Acknowledgments This book exists because of the efforts of Laura Lewin (my agent) and Peter Gordon, who believed strongly in the need for the book and convinced me to write it. Peter shaped its direction from the beginning, particularly with regard to the role of C/C++ issues and object-oriented programming. He was assisted by Bernard Gaffney, who shepherded the draft through its early stages of submission, review, and rewrites. Peter was also assisted by Chanda Leary-Coutu, who put together a great marketing plan, and Lara Wysong, the production coordinator. During copy editing and production, I was lucky enough to work with Kathy Glidden of Stratford Publishing Services and Brian Wright. They accommodated last-minute changes and a good deal of discussion on styles, even while under pressure to get a book out quickly. Many people contributed to the book through technical review and close examination of every line of code—saving the author from having to learn of certain errors after going to press. (Nothing is ever perfect, but the standard for this book was a “zero defect” goal in which we didn’t leave in obvious errors.) For some of these people I have only a last name, but among the most helpful reviewers were Mary Dageford, Bill Locke, Shauna Kelly, and Matthew Johnson. Matthew was especially helpful with his suggestion for an improved greatestcommon-factor algorithm. I think I once learned that algorithm in an advancedplacement math class, but that was more years ago than I’d like to admit. Dick Bower contributed the index, as well as finding some small errors that somehow got past everybody else. He showed that he obviously followed the text extremely well. I’d also like to thank Microsoft engineer John Bennett, who contributed useful insights on array indexing and random-number generation. Finally, I would especially like to thank my cousins Darren and Kevin Oke, who provided some of the earliest feedback and encouragement.

xxv

This page intentionally left blank

The accompanying CD-ROM contains a free C++ compiler—the software needed for programs to work. All the sample programs in this book are designed to run on any fairly recent C++ compiler. However, if you have a compiler released before 2000, it is possible that some examples might not run. If that happens, just move on to the next example—or install the compiler provided on the CD.

This page intentionally left blank

1

Your First C++ Programs There’s nothing to fear about C++ programming—really! Like all programming languages, it’s just a way to give logically precise directions to a computer. C++ can get as complicated as you want, but the easy way to start learning is to use it to solve fundamental programming tasks. That’s the approach here. In the first couple of sections, I review the basic concepts of programming. If you’ve programmed in any language, you might want to skip these, or review them briefly. But if you stick around, I promise to not be too long-winded.

Thinking like a Programmer Programming may not be exactly like any activity you’ve ever done. Basically, you’re just giving instructions—but doing so in a logical, systematic manner.

Computers Do Only What You Tell Them Computers do only what you tell them: This is the most important rule in this book, especially if you are new to programming. By using a computer language such as C++, Visual Basic, Pascal, or FORTRAN you give the computer a list of things to do; this is the program. I once ran a computer lab in Tacoma, Washington (famous for being America’s most stressful city). One of the students was a little man who wore a straw hat and old clothes. Every day he’d come to me with a stack of copies of The Daily Racing Form and say that if we could just enter that information into the computer we could make millions of dollars getting it to pick winning horses for us. That’s not how it works. A computer needs information, of course—that’s program data. But it also needs to know what to do with that data. The instructions that tell it what to do (for reasons I’ll go into later) are called program code.

1

2

Chapter 1

Your First C++ Programs

Determine What the Program Will Do So, to get a computer to do anything it has to be told exactly what to do. Up until now, you’ve probably used a computer by running programs other people (such as Bill Gates and his friends) have written for you. To this extent you’ve been an end user—commonly referred to as a user for short. Now, by writing programs yourself, you’ll promote yourself into the next higher echelon of computer people. Now you’ll decide what a program does. You’ll make things happen. But a computer—more so than Dustin Hoffman in Rain Man—is the ultimate idiot savant. It can never guess what you want. It can never make independent judgments. It is extremely literal and will carry out precisely what you tell it to do, no matter how stupid. Therefore, you have to be careful to say what you mean. You can’t even give the computer a command that might seem relatively clear to a human such as,“Convert a number from Celsius to Fahrenheit for me.” Even that’s too general. Instead, you have to be more specific, writing down steps such as these: 1 Print the message “Enter Celsius temperature: ” 2 Get a number from the keyboard and store it in the variable ctemp. 3 Convert to Fahrenheit by using the formula ftemp = (ctemp * 1.8) + 32. 4 Print the message “The Fahrenheit temperature is: ” 5 Print the value of the variable ftemp.

If you have to go through this much trouble just to do something simple, why even bother? The answer is that once a program is written you can run it over and over. And though programs take time to write, they usually execute at lightning speed.

Write the Equivalent C++ Statements After you’ve determined precisely what you want your program to do, step by step, you need to write down the equivalent C++ statements. A statement is roughly the C++ equivalent of a sentence in English; it can perform one or more actions or it can create a piece of data—as you’ll see later in the chapter. For example, say you want your program to do the following: 1 Print the message “The Fahrenheit temperature is: ” 2 Print the value of the variable ftemp.

Thinking like a Programmer

3

You’d translate these steps into the following C++ statements:

Remember, the goal of programming is to get the computer to do a series of specific tasks. But the computer understands only its own native language— machine code—which consists of 1s and 0s. Back in the 1950s, programmers did write out instructions in machine code, but this was exceedingly difficult and time-consuming. To make things easier, computer engineers developed programming languages such as FORTRAN, Basic, and C, which enabled humans to write programs bearing at least some resemblance to English. To write a program, you may want to start by writing pseudocode—an approach I often use in this book. Pseudocode is similar to English, but it describes the action of the program in a systematic way that reflects the logical flow of the program. For example, here’s a simple program written in pseudocode. If a is greater than b Print “a is greater than b.” Else Print “a is not greater than b.” Once you’ve written pseudocode, you’re not far from having a C++ program. All you need to do is look up the corresponding C++ statement for each action. if (a > b) cout > n; i = 1; while (i > n; // Test for prime-ness by checking for divisibility // by all whole numbers from 2 to sqrt(n). for (i = 2; i