Teach Yourself C++ in 21 Days
Jesse Liberty
This book is dedicated to the living memory of David Levine.
Copyright © 1994 by Sams Publishing
FIRST EDITION
All rights reserved. No part of this book shall be reproduced, stored
in a retrieval system, or transmitted by any means, electronic, mechanic
al, 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
responsibility for errors or omissions. Neither is any liability as sued
for damages resulting from the use of the information contained herein.
For information, address Sams Publishing, 201 W. 103rd St., Indianapolis,
IN 46290.
International Standard Book Number: 0-672-30541-0
Library of Congress Catalog Card Number: 94-66277
97 96 95 4 3 2
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 94-1 shows that
the first printing of the book occurred in 1994.
Composed in AGaramond and MCPdigital by Macmillan Computer Publishing
Printed in the United States of America
Trademarks
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
Richard K. Swadley
Associate Publisher
Jordan Gold
Acquisitions Manager
Stacy Hiquet
Managing Editor
Cindy Morrow
Acquisitions Editor
Christopher Denny
Development Editor
Brad Jones
Production Editor
Matthew Usher
Editors
Cheri Clark
Gregory A. Horman
Sean Medlock
Tonya R. Simpson
Editorial Coordinator
Bill Whitmer
Editorial Assistants
Carol Ackerman
Sharon Cox
Lynette Quinn
Technical Reviewer
Scott Parker
Marketing Manager
Gregg Bushyeager
Cover Designer
Dan Armstrong
Book Designer
Michele Laseau
Alyssa Yesh
Director of Production and Manufacturing
Jeff Valler
Imprint Manager
Juli Cook
Manufacturing Coordinator
Paul Gilchrist
Production Analysts
Dennis Clay Hager
Mary Beth Wakefield
Graphics Image Specialists
Tim Montgomery
Dennis Sheehan
Susan VandeWalle
Production
Georgiana Briggs
Michael Brumitt
Mona Brown
Elaine Brush
Cheryl Cameron
Mary Ann Cosby
Elaine Crabtree
Jamie Milazzo
Brian-Kent Proffitt
Caroline Roop
Kim Scott
Marc Shecter
SA Springer
Suzanne Tully
Indexer
Jeanne Clark
Overview
Week 1 at a Glance 1
Day 1 Getting Started 3
2 The Parts of a Program 19
3 Variables and Constants 33
4 Expressions and Statements 55
5 Functions 85
6 Basic Classes 123
7 More Program Flow 157
Week 1 in Review 189
Week 2 at a Glance 195
Day 8 Pointers 197
9 References 227
10 Advanced Functions 261
11 Arrays 299
12 Inheritance 337
13 Polymorphism 371
14 Special Classes and Functions 407
Week 2 in Review 435
Week 3 at a Glance 445
Day 15 Advanced Inheritance 447
16 Streams 485
17 The Preprocessor 525
18 Object-Oriented Analysis and Design 553
19 Templates 585
20 Exceptions and Error Handling 615
21 What's Next 643
Week 3 in Review 673
Appendixes
A Operator Precedence 685
B C++ Keywords 687
C Binary and Hexadecimal 689
D Answers 699
Index 789
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, Sa
ngam 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, including Christopher Denny, Bradley Jones, and Matthew Usher. 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.
About the Author
Jesse Liberty
Jesse Liberty has been programming computers professionally for over ten years. He is a Software Architect at AT&T Interchange Online Network, where he was a founding member of the Software Development Team. He is also president of The Liberty Group, Inc., and a former vice president of Citibank's Development Division. Jesse lives with his wife, Stacey, and his daughter, Robin, in the suburbs of Cambridge, Massachusetts. He can be reached via the Internet at jliberty@zdi.ziff.com.
About This Book
This book is designed to help you teach yourself how to program with C++.
In just 21 days, you'll learn about such fundamentals as the managing I/O, loops and arrays, object-oriented programming, templates, and creating C++ applicationsall in well-structured and easy-to-follow lessons. Lessons provide sample listingscomplete with sample output and an analysis of the codeto illustrate the topics of the day. Syntax examples are clearly
marked for handy reference.
To help you become more proficient, each lesson ends with a set of common questions and answers, exercises, and a quiz. You can check your progress by examining the quiz and exercise answers provided in the book's appendix.
Who Should Read This Book
You don't need any previous experience in programming to learn C++ with this book. This book starts you from the beginning and teaches you both the language and the concepts involved with programming C++. You'll find the numerous examples of syntax and detailed analysis of code an excellent guide as you begin your journey into this rewarding environment. Whether you are just beginning or already have some experience programming, you will find that this book's clear organization makes learning C++ fast and easy.
Conventions
Note: These boxes highlight information that can make your
C++ programming more efficient and effective.
Warning: These focus your attention on problems or
side effects that can occur in specific situations.
New Term: These boxes provide clear definitions of
essential terms.
DO use the "Do/Don't" boxes to find a
quick summary of a fundamental principle in a lesson.
DON'T overlook the useful information offered in these
boxes.
This book uses various typefaces to help you distinguish C++ code from
regular English. Actual C++ code is typeset in a special monospace font.
Placeholders words or characters temporarily used to represent the real
words or characters you would type in code are typeset in italic
monospace New or important terms are typeset in italic.
In the listings in this book, each real code line is numbered. If you
see an unnumbered line in a listing, you'll know that the unnumbered line
is really a continuation of the preceding numbered code line (some code
lines are too long for the width of the book). In this case, you should t
ype the two lines as one; do not divide them.
Contents
Week 1 at a Glance 1
Day 1 Getting Started 3
Introduction 4
A Brief History of C++ 4
The Word "Program" 5
Solving Problems 5
Procedural, Structured, and Object-Oriented Programming 6
C++ and Object-Oriented Programming 7
How C++ Evolved 9
Should I Learn C First? 9
Preparing to Program 9
Your Development Environment 10
Compiling the Source Code 11
Creating an Executable File with the Linker 12
The Development Cycle 12
HELLO.CPP -- Your First C++ Program 13
Compile Errors 15
Summary 15
Q&A 16
Workshop 16
Quiz 17
Exercises 17
2 The Parts of a C++ Program 19
Introduction 20
The Parts of a Simple Program 20
A Brief Look at cout 21
Comments 23
Types of Comments 23
Using Comments 24
Comments at the Top of Each File 25
A Final Word of Caution About Comments 26
Functions 26
Using Functions 27
Summary 29
Q&A 29
Workshop 30
Quiz 30
Exercises 30
3 Variables and Constants 33
What Is a Variable? 34
Setting Aside Memory 35
Size of Integers 35
Signed and Unsigned 36
Fundamental Variable Types 36
Defining a Variable 38
Case Sensitivity 39
Keywords 40
Creating More Than One Variable at a Time 40
Assigning Values to Your Variables 40
typedef 42
When to Use Short and When to Use Long 43
Wrapping Around in Unsigned Integers 43
Wrapping Around a Signed Integer 44
Characters 45
chars and Numbers 46
Special Printing Characters 46
Constants 47
Literal Constants 47
Symbolic Constants 48
Enumerated Constants 49
Summary 51
Q&A 52
Workshop 53
Quiz 53
Exercises 54
4 Expressions and Statements 55
Introduction 56
Statements 56
Whitespace 56
Blocks and Compound Statements 57
Expressions 57
Operators 59
Assignment Operator 59
Mathematical Operators 59
Integer Division and Modulus 60
Combining the Assignment and Mathematical Operators 61
Increment and Decrement 62
Prefix and Postfix 62
Precedence 64
Nesting Parentheses 65
The Nature of Truth 66
Relational Operators 66
The if Statement 67
Indentation Styles 70
else 70
Advanced if Statements 72
Use Braces in Nested if Statements 74
Logical Operators 76
Logical AND 77
Logical OR 77
Logical NOT 77
Relational Precedence 77
More About Truth and Falsehood 78
Conditional (Ternary) Operator 79
Summary 80
Q&A 81
Workshop 82
Quiz 82
Exercises 82
5 Functions 85
Introduction 86
What Is a Function? 86
Declaring and Defining Functions 87
Declaring the Function 87
Function Prototypes 88
Defining the Function 90
Execution of Functions 91
Local Variables 92
Global Variables 94
Global VariablesA Word of Caution 95
More on Local Variables 96
Function Statements 97
Function Arguments 98
Using Functions as Parameters to Functions 98
Parameters Are Local Variables 98
Return Values 100
Default Parameters 102
Overloading Functions 104
Special Topics 107
Inline Functions 107
Recursion 109
Summary 112
Q&A 113
Workshop 114
Quiz 114
Exercises 114
Extra Credit 116
How Functions Work 116
Levels of Abstraction 116
Partitioning RAM 116
The Stack and Functions 119
Quiz 120
Exercises 121
6 Basic Classes 123
Creating New Types 124
Why Create a New Type? 124
Classes and Members 125
Declaring a Class 125
A Word on Naming Conventions 126
Defining an Object 127
Classes Versus Objects 127
Accessing Class Members 127
Assign to Objects, Not to Classes 127
If You Don't Declare It, Your Class Won't Have It 128
Private Versus Public 129
Make Member Data Private 131
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 144
Inline Implementation 145
Classes with Other Classes as Member Data 148
Structures 151
Why Two Keywords Do the Same Thing 152
Summary 152
Q&A 153
Workshop 154
Quiz 154
Exercises 155
7 More Program Flow 157
Introduction 158
Looping 158
The Roots of Looping: goto 158
Why goto Is Shunned 159
while Loops 160
More Complicated while Statements 161
continue and break 163
while (1) Loops 165
do...while Loops 167
do...while 168
for Loops 170
Advanced for Loops 172
Empty for Loops 175
Nested Loops 175
Scoping in for Loops 177
Summing Up Loops 177
switch Statements 180
Using a switch Statement with a Menu 183
Summary 186
Q&A 186
Workshop 187
Quiz 187
Exercises 187
Week 1 in Review 189
Week 2 at a Glance 195
Day 8 Pointers 197
What Is a Pointer? 198
Storing the Address in a Pointer 200
Pointer Names 201
The Indirection Operator 201
Pointers, Addresses, and Variables 202
Manipulating Data by Using Pointers 203
Examining the Address 204
Why Would You Use Pointers? 206
The Stack and the Free Store 207
new 208
delete 209
Memory Leaks 211
Creating Objects on the Free Store 212
Deleting Objects 212
Accessing Data Members 213
Member Data on the Free Store 215
The this Pointer 216
Stray or Dangling Pointers 218
const Pointers 220
const Pointers and const Member Functions 221
const this Pointers 222
Summary 223
Q&A 223
Workshop 224
Quiz 224
Exercises 224
9 References 227
Introduction 228
What Is a Reference? 228
Using the Address of Operator & on References 229
What Can Be Referenced? 232
Null Pointers and Null References 234
Passing Function Arguments by Reference 234
Making swap() Work with Pointers 236
Implementing swap() with References 237
Understanding Function Headers and Prototypes 238
Returning Multiple Values 239
Returning Values by Reference 241
Passing by Reference for Efficiency 242
Passing a const Pointer 245
Referencing as an Alternative 247
When to Use References and When to Use Pointers 249
Mixing References and Pointers 250
Don't Return a Reference to an Object that Isn't in Scope! 252
Returning a Reference to an Object on the Heap 253
Pointer, Pointer, Who Has the Pointer? 256
Summary 256
Q&A 257
Workshop 257
Quiz 258
Exercises 258
10 Advanced Functions 261
Introduction 262
Overloaded Member Functions 262
Using Default Values 264
Choosing Between Default Values and Overloaded Functions 266
The Default Constructor 267
Overloading Constructors 267
Initializing Objects 269
The Copy Constructor 270
Operator Overloading 274
Writing an Increment Function 275
Overloading the prefix Operator 276
Returning Types in Overloaded Operator Functions 278
Returning Nameless Temporaries 279
Using the this Pointer 281
Overloading the postfix Operator 282
Operator+ 284
Overloading operator+ 286
Issues in Operator Overloading 287
Limitations on Operator Overloading 288
What to Overload 288
operator= 288
Conversion Operators 291
Operator unsigned short() 293
Summary 294
Q&A 295
Workshop 296
Quiz 296
Exercises 297
11 Arrays 299
What Is an Array? 300
Array Elements 301
Writing Past the End of an Array 302
Fence Post Errors 305
Initializing Arrays 305
Declaring Arrays 307
Arrays of Objects 308
Multidimensional Arrays 309
Initializing Multidimensional Arrays 310
A Word About Memory 312
Arrays of Pointers 312
Declaring Arrays on the Free Store 314
A Pointer to an Array Versus an Array of Pointers 314
Pointers and Array Names 315
Deleting Arrays on the Free Store 316
char Arrays 317
strcpy() and strncpy() 319
String Classes 321
Linked Lists and Other Structures 327
Array Classes 334
Summary 334
Q&A 335
Workshop 335
Quiz 336
Exercises 336
12 Inheritance 337
Introduction 338
What is Inheritance? 338
Inheritance and Derivation 338
The Animal Kingdom 340
The Syntax of Derivation 340
Private Versus Protected 342
Constructors and Destructors 344
Passing Arguments to Base Constructors 346
Overriding Functions 350
Overloading Versus Overriding 352
Hiding the Base Class Method 352
Calling the Base Method 353
Virtual Methods 355
How Virtual Functions Work 359
You Can't Get There from Here 360
Slicing 361
Virtual Destructors 363
Virtual Copy Constructors 363
The Cost of Virtual Methods 366
Summary 367
Q&A 368
Workshop 368
Quiz 369
Exercises 369
13 Polymorphism 371
Introduction 372
Problems with Single Inheritance 372
Percolating Upward 374
Casting Down 375
Adding to Two Lists 377
Multiple Inheritance 377
The Parts of a Multiply Inherited Object 380
Constructors in Multiply Inherited Objects 381
Ambiguity Resolution 383
Inheriting from Shared Base Class 384
Virtual Inheritance 388
Problems with Multiple Inheritance 391
Mixins and Capabilities Classes 392
Abstract Data Types 393
Pure Virtual Functions 396
Implementing Pure Virtual Functions 397
Complex Hierarchies of Abstraction 400
Which Types Are Abstract? 404
Q&A 404
Workshop 406
Quiz 406
Exercises 406
14 Special Classes and Functions 407
Static Member Data 408
Static Member Functions 413
Pointers to Functions 415
Why Use Function Pointers? 418
Arrays of Pointers to Functions 421
Passing Pointers to Functions to Other Functions 423
Using typedef with Pointers to Functions 425
Pointers to Member Functions 426
Arrays of Pointers to Member Functions 429
Summary 431
Q&A 431
Workshop 432
Quiz 432
Exercises 432
Week 2 in Review 435
Week 3 at a Glance 445
Day 15 Advanced Inheritance 447
Containment 448
Accessing Members of the Contained Class 454
Filtering Access to Contained Members 454
Cost of Containment 454
Copying by Value 456
Implemented in Terms of Versus Delegation 458
Delegation 459
Private Inheritance 464
Friend Classes 468
Friend Functions 475
Friend Functions and Operator Overloading 475
Overloading the Insertion Operator 478
Summary 480
Q&A 480
Workshop 481
Quiz 481
Exercises 482
16 Streams 485
Overview of Streams 486
Encapsulation 486
Buffering 487
Streams and Buffers 490
Standard I/O Objects 490
Redirection 491
Input Using cin 491
Strings 493
String Problems 493
operator>> Returns a Reference to an istream Object 496
Other Member Functions of cin 496
Single Character Input 496
Getting Strings from Standard Input 499
Using cin.ignore() 501
peek() and putback() 503
Output with cout 504
Flushing the Output 504
Related Functions 504
Manipulators, Flags, and Formatting Instructions 506
Using cout.width() 506
Setting the Fill Characters 507
Set Flags 508
Streams Versus the printf() Function 510
File Input and Output 512
ofstream 512
Condition States 513
Opening Files for Input and Output 513
Changing the Default Behavior of ofstream on Open 515
Binary Versus Text Files 517
Command-Line Processing 519
Summary 522
Q&A 523
Workshop 523
Quiz 524
Exercises 524
17 The Preprocessor 525
The Preprocessor and the Compiler 526
Seeing the Intermediate Form 526
Using #define 526
Using #define for Constants 527
Using #define for Tests 527
The #else Precompiler Command 528
Inclusion and Inclusion Guards 529
Defining on the Command Line 530
Undefining 530
Conditional Compilation 532
Macro Functions 532
Why All the Parentheses? 533
Macros Versus Functions and Templates 535
Inline Functions 535
String Manipulation 537
Stringizing 537
Concatenation 537
Predefined Macros 538
assert() 538
Debugging with assert() 540
assert() Versus Exceptions 540
Side Effects 541
Class Invariants 541
Printing Interim Values 546
Debugging Levels 547
Summary 550
Q&A 551
Workshop 552
Quiz 552
Exercises 552
18 Object-Oriented Analysis and Design 553
The Development Cycle 554
Simulating an Alarm System 555
Preliminary Design 555
What Are the Objects? 556
Other Objects 556
What Are the Classes? 557
How Are Alarms Reported? 558
Event Loops 558
PostMaster 561
Measure Twice, Cut Once 561
Divide and Conquer 562
Message Format 563
Initial Class Design 564
Rooted Hierarchies Versus Non-Rooted 565
Designing the Interfaces 567
Building a Prototype 568
The 80/80 Rule 569
Designing the PostMasterMessage Class 570
Application Program Interface 570
Programming in Large Groups 571
Ongoing Design Considerations 572
Design Decisions 572
Decisions, Decisions 572
Working with Driver Programs 574
Summary 580
Q&A 581
Workshop 582
Quiz 582
Exercises 582
19 Templates 585
What are Templates? 586
Parameterized Types 586
Template Definition 587
Using the Name 589
Implementing the Template 589
Template Functions 592
Templates and Friends 593
Non-Template Friend Classes and Functions 593
General Template Friend Class or Function 596
A Type-Specific Template Friend Class or Function 598
Using Template Items 599
Specialized Functions 602
Static Members and Templates 608
Summary 611
Q&A 611
Workshop 612
Quiz 612
Exercises 613
20 Exceptions and Error Handling 615
Introduction 616
Bugs, Errors, Mistakes, and Code Rot 616
Exceptions 617
A Word About Code Rot 618
Exceptions 618
How Exceptions Are Used 619
Using try Blocks and catch Blocks 624
Catching Exceptions 624
More Than One catch Specification 625
Exception Hierarchies 627
Data in Exceptions and Naming Exception Objects 629
Exceptions and Templates 634
Exceptions Without Errors 637
Bugs and Debugging 638
Breakpoints 638
Watch Points 639
Examining Memory 639
Assembler 639
Summary 639
Q&A 640
Workshop 641
Quiz 641
Exercises 641
21 What's Next 643
Introduction 644
The Standard Libraries 644
String 644
strcpy() and strncpy() 645
strcat() and strncat() 648
Other String Functions 649
Time and Date 650
stdlib 651
qsort() 652
Other Libraries 654
Bit Twiddling 654
Operator AND 655
Operator OR 655
Operator Exclusive OR 656
The Complement Operator 656
Setting Bits 656
Clearing Bits 656
Flipping Bits 657
Bit Fields 657
Style 660
Indenting 660
Braces 661
Long Lines 661
switch Statements 661
Program Text 662
Identifier Names 662
Spelling and Capitalization of Names 663
Comments 664
Access 664
Class Definitions 665
include Files 665
assert() 666
const 666
Next Steps 666
Where to Get Help and Advice 666
Required Reading 667
Object-Oriented Analysis and Design 667
Writing Solid Code 667
Data Structures 667
Windows and Mac 668
Magazines 668
Staying in Touch 668
Summary 669
Q&A 669
Quiz 670
Exercises 671
Week 3 in Review 673
Appendixes
A Operator Precedence 685
Introduction 686
B C++ Keywords 687
Introduction 688
C Binary and Hexadecimal 689
Introduction 690
Other Bases 690
Around the Bases 691
Binary 692
Why Base Two? 693
Bits, Bytes, and Nybbles 693
What's a K? 694
Binary Numbers 694
Hexadecimal 694
D Answers 699
Index 789