C++
Jesse LibertyBradley Jones
FIFTH EDITION
Teach Yourself
in21Days800 East 96th Street, Indianapolis, Indiana, 46240 USA
00 0672327112_fm.qxd 11/19/04 12:52 PM Page i
Sams Teach Yourself C++ in 21 Days,Fifth EditionCopyright 2005 by Sams PublishingAll rights reserved. No part of this book shall be reproduced, stored in aretrieval system, or transmitted by any means, electronic, mechanical, photo-copying, recording, or otherwise, without written permission from the pub-lisher. No patent liability is assumed with respect to the use of the informationcontained herein. Although every precaution has been taken in the preparationof this book, the publisher and author assume no responsibility for errors oromissions. Nor is any liability assumed for damages resulting from the use ofthe information contained herein.
International Standard Book Number: 0-672-32711-2
Library of Congress Catalog Card Number: 2004096713
Printed in the United States of America
First Printing: December 2004
07 06 05 04 4 3 2 1
TrademarksAll terms mentioned in this book that are known to be trademarks or servicemarks have been appropriately capitalized. Sams Publishing cannot attest tothe accuracy of this information. Use of a term in this book should not beregarded as affecting the validity of any trademark or service mark.
Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied. The information provided is onan as is basis. The authors and the publisher shall have neither liability norresponsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.
Bulk SalesSams Publishing 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 [email protected]
For sales outside of the U.S., please contact
International [email protected]
ASSOCIATE PUBLISHERMichael Stephens
ACQUISITIONS EDITORLoretta Yates
DEVELOPMENT EDITORSonglin Qiu
MANAGING EDITORCharlotte Clapp
PROJECT EDITORSeth Kerney
COPY EDITORKaren Annett
INDEXERErika Millen
PROOFREADERPaula Lowell
TECHNICAL EDITORSMark CashmanDavid V. Corbin
PUBLISHING COORDINATORCindy Teeters
MULTIMEDIA DEVELOPERDan Scherf
BOOK DESIGNERGary Adair
PAGE LAYOUTEric S. MillerJulie Parks
00 0672327112_fm.qxd 11/19/04 12:52 PM Page ii
Contents at a GlanceIntroduction 1
Week 1 At a Glance 3
Day 1 Getting Started 5
2 The Anatomy of a C++ Program 25
3 Working with Variables and Constants 41
4 Creating Expressions and Statements 67
5 Organizing into Functions 99
6 Understanding Object-Oriented Programming 137
7 More on Program Flow 175
Week 1 In Review 209
Week 2 At a Glance 219
Day 8 Understanding Pointers 221
9 Exploiting References 255
10 Working with Advanced Functions 289
11 Object-Oriented Analysis and Design 329
12 Implementing Inheritance 371
13 Managing Arrays and Strings 407
14 Polymorphism 449
Week 2 In Review 491
Week 3 At a Glance 503
Day 15 Special Classes and Functions 505
16 Advanced Inheritance 537
17 Working with Streams 593
18 Creating and Using Namespaces 637
19 Templates 659
20 Handling Errors and Exceptions 715
21 Whats Next 751
00 0672327112_fm.qxd 11/19/04 12:52 PM Page iii
Week 3 In Review 791
Appendixes
Appendix A Working with Numbers: Binary and Hexadecimal 807
B C++ Keywords 817
C Operator Precedence 819
D Answers 821
E A Look at Linked Lists 875
Index 887
00 0672327112_fm.qxd 11/19/04 12:52 PM Page iv
ContentsIntroduction 1
Who Should Read This Book ..................................................................................1Conventions Used in This Book ..............................................................................1Sample Code for This Book ....................................................................................2
Week 1 At a Glance 3
A Note to C Programmers ......................................................................................3Where You Are Going..............................................................................................3
1 Getting Started 5
A Brief History of C++ ..........................................................................................5The Need for Solving Problems ........................................................................7Procedural, Structured, and Object-Oriented Programming ..............................8Object-Oriented Programming (OOP) ..............................................................9C++ and Object-Oriented Programming............................................................9
How C++ Evolved ................................................................................................11Should I Learn C First? ........................................................................................11C++, Java, and C#..................................................................................................12Microsofts Managed Extensions to C++..............................................................12The ANSI Standard................................................................................................12Preparing to Program ............................................................................................13Your Development Environment ..........................................................................14The Process of Creating the Program....................................................................15
Creating an Object File with the Compiler ......................................................15Creating an Executable File with the Linker ..................................................15
The Development Cycle ........................................................................................16HELLO.cppYour First C++ Program ..................................................................17Getting Started with Your Compiler ......................................................................19
Building the Hello World Project ....................................................................19Compile Errors ......................................................................................................20Summary ................................................................................................................21Q&A ......................................................................................................................21Workshop ..............................................................................................................22
Quiz ..................................................................................................................22Exercises ..........................................................................................................23
2 The Anatomy of a C++ Program 25
A Simple Program ................................................................................................25A Brief Look at cout ............................................................................................28
00 0672327112_fm.qxd 11/19/04 12:52 PM Page v
Using the Standard Namespace ............................................................................30Commenting Your Programs..................................................................................32
Types of Comments..........................................................................................33Using Comments ..............................................................................................33A Final Word of Caution About Comments ....................................................34
Functions................................................................................................................35Using Functions................................................................................................36Methods Versus Functions................................................................................38
Summary ................................................................................................................38Q&A ......................................................................................................................38Workshop ..............................................................................................................39
Quiz ..................................................................................................................39Exercises ..........................................................................................................39
3 Working with Variables and Constants 41
What Is a Variable? ................................................................................................41Storing Data in Memory ..................................................................................42Setting Aside Memory......................................................................................42Size of Integers ................................................................................................43signed and unsigned ........................................................................................45Fundamental Variable Types ............................................................................45
Defining a Variable ................................................................................................47Case Sensitivity ................................................................................................48Naming Conventions ........................................................................................48Keywords ..........................................................................................................49
Creating More Than One Variable at a Time ........................................................50Assigning Values to Your Variables ......................................................................50Creating Aliases with typedef ..............................................................................52When to Use short and When to Use long ..........................................................53
Wrapping Around an unsigned Integer............................................................54Wrapping Around a signed Integer..................................................................55
Working with Characters ......................................................................................56Characters and Numbers ..................................................................................57Special Printing Characters ..............................................................................58
Constants................................................................................................................59Literal Constants ..............................................................................................59Symbolic Constants ..........................................................................................59
Enumerated Constants ..........................................................................................61Summary ................................................................................................................63Q&A ......................................................................................................................64Workshop ..............................................................................................................65
Quiz ..................................................................................................................65Exercises ..........................................................................................................66
vi Sams Teach Yourself C++ in 21 Days, Fifth Edition
00 0672327112_fm.qxd 11/19/04 12:52 PM Page vi
4 Creating Expressions and Statements 67
Starting with Statements ........................................................................................68Using Whitespace ............................................................................................68Blocks and Compound Statements ..................................................................68
Expressions ............................................................................................................69Working with Operators ........................................................................................70
Assignment Operators ......................................................................................71Mathematical Operators ..................................................................................71
Combining the Assignment and Mathematical Operators ....................................73Incrementing and Decrementing............................................................................74
Prefixing Versus Postfixing ..............................................................................75Understanding Operator Precedence ....................................................................77Nesting Parentheses ..............................................................................................78The Nature of Truth ..............................................................................................79
Evaluating with the Relational Operators ........................................................79The if Statement ..................................................................................................80
Indentation Styles ............................................................................................83The else Statement ..........................................................................................84Advanced if Statements ..................................................................................86
Using Braces in Nested if Statements ..................................................................88Using the Logical Operators..................................................................................91
The Logical AND Operator ................................................................................91The Logical OR Operator ..................................................................................91The Logical NOT Operator ................................................................................92
Short Circuit Evaluation ........................................................................................92Relational Precedence............................................................................................92More About Truth and Falsehood..........................................................................93The Conditional (Ternary) Operator......................................................................94Summary ................................................................................................................95Q&A ......................................................................................................................96Workshop ..............................................................................................................96
Quiz ..................................................................................................................97Exercises ..........................................................................................................97
5 Organizing into Functions 99
What Is a Function? ............................................................................................100Return Values, Parameters, and Arguments ........................................................100Declaring and Defining Functions ......................................................................101
Function Prototypes........................................................................................102Defining the Function ....................................................................................103
Execution of Functions ........................................................................................105Determining Variable Scope ................................................................................105
Local Variables ..............................................................................................105Local Variables Within Blocks ......................................................................107
Contents vii
00 0672327112_fm.qxd 11/19/04 12:52 PM Page vii
Parameters Are Local Variables ..........................................................................109Global Variables..............................................................................................110Global Variables: A Word of Caution ............................................................112
Considerations for Creating Function Statements ..............................................112More About Function Arguments ........................................................................113More About Return Values ..................................................................................114Default Parameters ..............................................................................................116Overloading Functions ........................................................................................118Special Topics About Functions ..........................................................................121
Inline Functions ..............................................................................................122Recursion ........................................................................................................124
How Functions WorkA Peek Under the Hood ................................................129Levels of Abstraction......................................................................................129
Summary ..............................................................................................................133Q&A ....................................................................................................................134Workshop ............................................................................................................134
Quiz ................................................................................................................135Exercises ........................................................................................................135
6 Understanding Object-Oriented Programming 137
Is C++ Object-Oriented? ....................................................................................137Creating New Types ............................................................................................139Introducing Classes and Members ......................................................................140
Declaring a Class............................................................................................141A Word on Naming Conventions ..................................................................141Defining an Object ........................................................................................142Classes Versus Objects ..................................................................................142
Accessing Class Members ..................................................................................142Assigning to Objects, Not to Classes ............................................................143If You Dont Declare It, Your Class Wont Have It ........................................143
Private Versus Public Access ..............................................................................144Making Member Data Private ........................................................................146
Implementing Class Methods ..............................................................................150Adding Constructors and Destructors..................................................................153
Getting a Default Constructor and Destructor ..............................................153Using the Default Constructor........................................................................154
Including const Member Functions ....................................................................157Interface Versus Implementation ........................................................................158Where to Put Class Declarations and Method Definitions..................................161Inline Implementation..........................................................................................162Classes with Other Classes as Member Data ......................................................165Exploring Structures ............................................................................................169
viii Sams Teach Yourself C++ in 21 Days, Fifth Edition
00 0672327112_fm.qxd 11/19/04 12:52 PM Page viii
Summary ..............................................................................................................170Q&A ....................................................................................................................171Workshop ............................................................................................................172
Quiz ................................................................................................................172Exercises ........................................................................................................173
7 More on Program Flow 175
Looping ................................................................................................................175The Roots of Looping: goto ..........................................................................176Why goto Is Shunned ....................................................................................176
Using while Loops ..............................................................................................177Exploring More Complicated while Statements............................................179Introducing continue and break ....................................................................180Examining while (true) Loops....................................................................183
Implementing do...while Loops ........................................................................184Using do...while ................................................................................................186Looping with the for Statement ..........................................................................187
Advanced for Loops ......................................................................................190Empty for Loops............................................................................................192Nesting Loops ................................................................................................193Scoping in for Loops ....................................................................................195
Summing Up Loops ............................................................................................196Controlling Flow with switch Statements ..........................................................198
Using a switch Statement with a Menu ........................................................201Summary ..............................................................................................................205Q&A ....................................................................................................................205Workshop ............................................................................................................206
Quiz ................................................................................................................206Exercises ........................................................................................................206
Week 1 In Review 209
Week 2 At a Glance 219
Where You Are Going..........................................................................................219
8 Understanding Pointers 221
What Is a Pointer?................................................................................................222A Bit About Memory......................................................................................222Getting a Variables Memory Address............................................................222Storing a Variables Address in a Pointer ......................................................224Pointer Names ................................................................................................224Getting the Value from a Variable ..................................................................225Dereferencing with the Indirection Operator ................................................226Pointers, Addresses, and Variables ................................................................227
Contents ix
00 0672327112_fm.qxd 11/19/04 12:52 PM Page ix
Manipulating Data by Using Pointers ............................................................228Examining the Address ..................................................................................229
Why Would You Use Pointers?............................................................................232The Stack and the Free Store (Heap) ..................................................................232
Allocating Space with the new Keyword ........................................................234Putting Memory Back: The delete Keyword ................................................235
Another Look at Memory Leaks ........................................................................237Creating Objects on the Free Store......................................................................238Deleting Objects from the Free Store..................................................................238Accessing Data Members ....................................................................................239Creating Member Data on the Free Store............................................................241The this Pointer ..................................................................................................243Stray, Wild, or Dangling Pointers........................................................................245Using const Pointers ..........................................................................................248
const Pointers and const Member Functions................................................249Using a const this Pointers..........................................................................251
Summary ..............................................................................................................251Q&A ....................................................................................................................252Workshop ............................................................................................................252
Quiz ................................................................................................................252Exercises ........................................................................................................253
9 Exploiting References 255
What Is a Reference? ..........................................................................................255Using the Address-Of Operator (&) on References..............................................257
Attempting to Reassign References (Not!) ....................................................259Referencing Objects ............................................................................................260Null Pointers and Null References ......................................................................262Passing Function Arguments by Reference ........................................................262
Making swap() Work with Pointers ..............................................................264Implementing swap() with References ..........................................................265
Understanding Function Headers and Prototypes ..............................................267Returning Multiple Values ..................................................................................268
Returning Values by Reference ......................................................................270Passing by Reference for Efficiency....................................................................271
Passing a const Pointer ..................................................................................274References as an Alternative ..........................................................................277
Knowing When to Use References Versus Pointers ............................................279Mixing References and Pointers..........................................................................280Returning Out-of-Scope Object References ........................................................281
Returning a Reference to an Object on the Heap ..........................................283Pointer, Pointer, Who Has the Pointer? ..............................................................285
x Sams Teach Yourself C++ in 21 Days, Fifth Edition
00 0672327112_fm.qxd 11/19/04 12:52 PM Page x
Summary ..............................................................................................................286Q&A ....................................................................................................................286Workshop ............................................................................................................287
Quiz ................................................................................................................287Exercises ........................................................................................................287
10 Working with Advanced Functions 289
Overloaded Member Functions ..........................................................................289Using Default Values ..........................................................................................292Choosing Between Default Values and Overloaded Functions ..........................294The Default Constructor ......................................................................................294Overloading Constructors ....................................................................................295Initializing Objects ..............................................................................................297The Copy Constructor..........................................................................................298Operator Overloading ..........................................................................................302
Writing an Increment Function ......................................................................303Overloading the Prefix Operator ....................................................................304Returning Types in Overloaded Operator Functions......................................306Returning Nameless Temporaries ..................................................................307Using the this Pointer ..................................................................................309Overloading the Postfix Operator ..................................................................311Difference Between Prefix and Postfix ..........................................................311Overloading Binary Mathematical Operators ................................................313Issues in Operator Overloading......................................................................316Limitations on Operator Overloading ............................................................316What to Overload ..........................................................................................317The Assignment Operator ..............................................................................317
Handling Data Type Conversion..........................................................................320Conversion Operators ..........................................................................................323Summary ..............................................................................................................325Q&A ....................................................................................................................325Workshop ............................................................................................................326
Quiz ................................................................................................................326Exercises ........................................................................................................327
11 Object-Oriented Analysis and Design 329
Building Models ..................................................................................................329Software Design: The Modeling Language ........................................................330Software Design: The Process ............................................................................331
Waterfall Versus Iterative Development ........................................................332The Process of Iterative Development ..........................................................333
Step 1: The Conceptualization Phase: Starting with The Vision ........................335
Contents xi
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xi
Step 2: The Analysis Phase: Gathering Requirements ........................................336Use Cases........................................................................................................336Application Analysis ......................................................................................347Systems Analysis ............................................................................................347Planning Documents ......................................................................................348Visualizations..................................................................................................349Artifacts ..........................................................................................................349
Step 3: The Design Phase ....................................................................................350What Are the Classes?....................................................................................350Transformations..............................................................................................352Other Transformations....................................................................................353Building the Static Model ..............................................................................354Dynamic Model ..............................................................................................363
Steps 46: Implementation, Testing, and Rollout?..............................................366Iterations ..............................................................................................................367Summary ..............................................................................................................367Q&A ....................................................................................................................367Workshop ............................................................................................................368
Quiz ................................................................................................................368Exercises ........................................................................................................369
12 Implementing Inheritance 371
What Is Inheritance? ............................................................................................371Inheritance and Derivation ............................................................................372The Animal Kingdom ....................................................................................373The Syntax of Derivation ..............................................................................374
Private Versus Protected ......................................................................................376Inheritance with Constructors and Destructors ..................................................378
Passing Arguments to Base Constructors ......................................................381Overriding Base Class Functions ........................................................................385
Hiding the Base Class Method ......................................................................387Calling the Base Method ................................................................................389
Virtual Methods ..................................................................................................391How Virtual Functions Work..........................................................................395Trying to Access Methods from a Base Class................................................396Slicing ............................................................................................................397Creating Virtual Destructors ..........................................................................399Virtual Copy Constructors..............................................................................400The Cost of Virtual Methods ..........................................................................403
Summary ..............................................................................................................403Q&A ....................................................................................................................404Workshop ............................................................................................................405
xii Sams Teach Yourself C++ in 21 Days, Fifth Edition
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xii
Quiz ................................................................................................................405Exercises ........................................................................................................405
13 Managing Arrays and Strings 407
What Is an Array? ................................................................................................407Accessing Array Elements..............................................................................408Writing Past the End of an Array ..................................................................410Fence Post Errors............................................................................................413Initializing Arrays ..........................................................................................413Declaring Arrays ............................................................................................414
Using Arrays of Objects ......................................................................................416Declaring Multidimensional Arrays ..............................................................417Initializing Multidimensional Arrays ............................................................419
Building Arrays of Pointers ................................................................................421A Look at Pointer ArithmeticAn Advanced Topic ..........................................423Declaring Arrays on the Free Store ....................................................................426
A Pointer to an Array Versus an Array of Pointers ........................................426Pointers and Array Names..............................................................................427Deleting Arrays on the Free Store..................................................................429Resizing Arrays at Runtime............................................................................429
char Arrays and Strings ......................................................................................432Using the strcpy() and strncpy() Methods ......................................................435String Classes ......................................................................................................436Linked Lists and Other Structures ......................................................................444Creating Array Classes ........................................................................................444Summary ..............................................................................................................445Q&A ....................................................................................................................445Workshop ............................................................................................................446
Quiz ................................................................................................................446Exercises ........................................................................................................447
14 Polymorphism 449
Problems with Single Inheritance........................................................................449Percolating Upward ........................................................................................452Casting Down ................................................................................................453Adding to Two Lists ......................................................................................456
Multiple Inheritance ............................................................................................456The Parts of a Multiply Inherited Object ......................................................460Constructors in Multiply Inherited Objects....................................................460Ambiguity Resolution ....................................................................................463Inheriting from Shared Base Class ................................................................464Virtual Inheritance ..........................................................................................468Problems with Multiple Inheritance ..............................................................472Mixins and Capabilities Classes ....................................................................473
Contents xiii
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xiii
Abstract Data Types ............................................................................................473Pure Virtual Functions ....................................................................................477Implementing Pure Virtual Functions ............................................................478Complex Hierarchies of Abstraction ..............................................................482Which Classes Are Abstract? ........................................................................486
Summary ..............................................................................................................486Q&A ....................................................................................................................487Workshop ............................................................................................................488
Quiz ................................................................................................................488Exercises ........................................................................................................489
Week 2 In Review 491
Week 3 At a Glance 503
Where You Are Going..........................................................................................503
15 Special Classes and Functions 505
Sharing Data Among Objects of the Same Type: Static Member Data ..............506Using Static Member Functions ..........................................................................511Pointers to Functions ..........................................................................................514
Why Use Function Pointers?..........................................................................517Arrays of Pointers to Functions......................................................................521Passing Pointers to Functions to Other Functions ........................................523Using typedef with Pointers to Functions ....................................................525
Pointers to Member Functions ............................................................................528Arrays of Pointers to Member Functions ......................................................531
Summary ..............................................................................................................533Q&A ....................................................................................................................533Workshop ............................................................................................................534
Quiz ................................................................................................................534Exercises ........................................................................................................534
16 Advanced Inheritance 537
Aggregation..........................................................................................................537Accessing Members of the Aggregated Class................................................545Controlling Access to Aggregated Members..................................................545Cost of Aggregation........................................................................................546Copying by Value ..........................................................................................549
Implementation in Terms of Inheritance Versus Aggregation/Delegation ..........552Using Delegation ............................................................................................553
Private Inheritance ..............................................................................................562Adding Friend Classes ........................................................................................571Friend Functions ..................................................................................................580
xiv Sams Teach Yourself C++ in 21 Days, Fifth Edition
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xiv
Friend Functions and Operator Overloading ......................................................580Overloading the Insertion Operator ....................................................................585Summary ..............................................................................................................589Q&A ....................................................................................................................590Workshop ............................................................................................................591
Quiz ................................................................................................................591Exercises ........................................................................................................591
17 Working with Streams 593
Overview of Streams ..........................................................................................593Encapsulation of Data Flow ..........................................................................594Understanding Buffering ................................................................................594
Streams and Buffers ............................................................................................597Standard I/O Objects............................................................................................597Redirection of the Standard Streams ..................................................................598Input Using cin....................................................................................................599
Inputting Strings ............................................................................................600String Problems ..............................................................................................601The cin Return Value ....................................................................................603
Other Member Functions of cin..........................................................................604Single Character Input....................................................................................604Getting Strings from Standard Input ..............................................................607Using cin.ignore() ......................................................................................610Peeking at and Returning Characters: peek() and putback() ......................611
Outputting with cout ..........................................................................................613Flushing the Output ........................................................................................613Functions for Doing Output ..........................................................................613Manipulators, Flags, and Formatting Instructions ........................................615
Streams Versus the printf() Function................................................................620File Input and Output ..........................................................................................623Using the ofstream ..............................................................................................624
Condition States..............................................................................................624Opening Files for Input and Output ..............................................................624Changing the Default Behavior of ofstream on Open ..................................626
Binary Versus Text Files ......................................................................................629Command-line Processing ..................................................................................631Summary ..............................................................................................................634Q&A ....................................................................................................................635Workshop ............................................................................................................636
Quiz ................................................................................................................636Exercises ........................................................................................................636
Contents xv
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xv
18 Creating and Using Namespaces 637
Getting Started ....................................................................................................637Resolving Functions and Classes by Name ........................................................638
Visibility of Variables ....................................................................................640Linkage ..........................................................................................................641Static Global Variables ..................................................................................642
Creating a Namespace ........................................................................................643Declaring and Defining Types........................................................................644Defining Functions Outside a Namespace ....................................................645Adding New Members ..................................................................................645Nesting Namespaces ......................................................................................646
Using a Namespace..............................................................................................646The using Keyword ............................................................................................648
The using Directive........................................................................................648The using Declaration....................................................................................650
The Namespace Alias ..........................................................................................652The Unnamed Namespace ..................................................................................652The Standard Namespace std..............................................................................654Summary ..............................................................................................................655Q&A ....................................................................................................................656Workshop ............................................................................................................656
Quiz ................................................................................................................656Exercises ........................................................................................................657
19 Templates 659
What Are Templates? ..........................................................................................659Building a Template Definition ..........................................................................661
Using the Name ..............................................................................................664Implementing the Template............................................................................665
Passing Instantiated Template Objects to Functions ..........................................669Templates and Friends ........................................................................................670
Nontemplate Friend Classes and Functions ..................................................670General Template Friend Class or Function ..................................................674
Using Template Items ..........................................................................................678Using Specialized Functions ..........................................................................683Static Members and Templates ......................................................................689
The Standard Template Library ..........................................................................693Using Containers ............................................................................................693Understanding Sequence Containers..............................................................694Understanding Associative Containers ..........................................................704Working with the Algorithm Classes ............................................................708
Summary ..............................................................................................................711
xvi Sams Teach Yourself C++ in 21 Days, Fifth Edition
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xvi
Q&A ....................................................................................................................712Workshop ............................................................................................................713
Quiz ................................................................................................................713Exercises ........................................................................................................713
20 Handling Errors and Exceptions 715
Bugs, Errors, Mistakes, and Code Rot ................................................................716Exceptional Circumstances ............................................................................717
The Idea Behind Exceptions................................................................................718The Parts of Exception Handling ..................................................................719Causing Your Own Exceptions ......................................................................722Creating an Exception Class ..........................................................................724
Placing try Blocks and catch Blocks ................................................................728How Catching Exceptions Work..........................................................................728
Using More Than One catch Specification ..................................................729Exception Hierarchies ....................................................................................732
Data in Exceptions and Naming Exception Objects ..........................................735Exceptions and Templates ..................................................................................742Exceptions Without Errors ..................................................................................745A Word About Code Rot......................................................................................746Bugs and Debugging............................................................................................746
Breakpoints ....................................................................................................747Watch Points ..................................................................................................747Examining Memory........................................................................................747Assembler ......................................................................................................747
Summary ..............................................................................................................748Q&A ....................................................................................................................748Workshop ............................................................................................................749
Quiz ................................................................................................................749Exercises ........................................................................................................750
21 Whats Next 751
The Preprocessor and the Compiler ....................................................................752The #define Preprocessor Directive....................................................................752
Using #define for Constants..........................................................................753Using #define for Tests ................................................................................753The #else Precompiler Command ................................................................754
Inclusion and Inclusion Guards ..........................................................................755Macro Functions ..................................................................................................756
Why All the Parentheses? ..............................................................................757String Manipulation ............................................................................................759
Stringizing ......................................................................................................759Concatenation ................................................................................................759
Contents xvii
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xvii
Predefined Macros ..............................................................................................760The assert() Macro............................................................................................761
Debugging with assert() ..............................................................................762Using assert() Versus Exceptions ................................................................763Side Effects ....................................................................................................763Class Invariants ..............................................................................................764Printing Interim Values ..................................................................................769
Inline Functions ..................................................................................................771Bit Twiddling ......................................................................................................773
Operator AND ................................................................................................773Operator OR ..................................................................................................774Operator Exclusive OR ..................................................................................774The Complement Operator ............................................................................774Setting Bits ....................................................................................................774Clearing Bits ..................................................................................................774Flipping Bits ..................................................................................................775Bit Fields ........................................................................................................775
Programming Style ..............................................................................................779Indenting ........................................................................................................779Braces ............................................................................................................779Long Lines and Function Length ..................................................................780Structuring switch Statements ......................................................................780Program Text ..................................................................................................780Naming Identifiers..........................................................................................781Spelling and Capitalization of Names............................................................782Comments ......................................................................................................782Setting Up Access ..........................................................................................783Class Definitions ............................................................................................783include Files ..................................................................................................784Using assert() ..............................................................................................784Making Items Constant with const................................................................784
Next Steps in Your C++ Development ................................................................784Where to Get Help and Advice ......................................................................785Related C++ Topics: Managed C++, C#, and Microsofts .NET ..................785Staying in Touch ............................................................................................786
Summary ..............................................................................................................786Q&A ....................................................................................................................787Workshop ............................................................................................................788
Quiz ................................................................................................................788Exercises ........................................................................................................789
Week 3 In Review 791
xviii Sams Teach Yourself C++ in 21 Days, Fifth Edition
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xviii
A Working with Numbers: Binary and Hexadecimal 807
Using Other Bases ..............................................................................................808Converting to Different Bases ............................................................................809
Binary ............................................................................................................810Why Base 2? ..................................................................................................811Bits, Bytes, and Nybbles ................................................................................812Whats a KB?..................................................................................................812Binary Numbers..............................................................................................812
Hexadecimal ........................................................................................................813
B C++ Keywords 817
C Operator Precedence 819
D Answers 821
Day 1....................................................................................................................821Quiz ................................................................................................................821Exercises ........................................................................................................822
Day 2....................................................................................................................822Quiz ................................................................................................................822Exercises ........................................................................................................823
Day 3....................................................................................................................824Quiz ................................................................................................................824Exercises ........................................................................................................825
Day 4....................................................................................................................825Quiz ................................................................................................................825Exercises ........................................................................................................826
Day 5....................................................................................................................826Quiz ................................................................................................................826Exercises ........................................................................................................827
Day 6....................................................................................................................829Quiz ................................................................................................................829Exercises ........................................................................................................829
Day 7....................................................................................................................832Quiz ................................................................................................................832Exercises ........................................................................................................832
Day 8....................................................................................................................833Quiz ................................................................................................................833Exercises ........................................................................................................834
Day 9....................................................................................................................835Quiz ................................................................................................................835Exercises ........................................................................................................835
Contents xix
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xix
Day 10..................................................................................................................837Quiz ................................................................................................................837Exercises ........................................................................................................838
Day 11..................................................................................................................842Quiz ................................................................................................................842Exercises ........................................................................................................842
Day 12..................................................................................................................846Quiz ................................................................................................................846Exercises ........................................................................................................846
Day 13..................................................................................................................847Quiz ................................................................................................................847Exercises ........................................................................................................847
Day 14..................................................................................................................848Quiz ................................................................................................................848Exercises ........................................................................................................849
Day 15..................................................................................................................850Quiz ................................................................................................................850Exercises ........................................................................................................850
Day 16..................................................................................................................856Quiz ................................................................................................................856Exercises ........................................................................................................856
Day 17..................................................................................................................859Quiz ................................................................................................................859Exercises ........................................................................................................860
Day 18..................................................................................................................862Quiz ................................................................................................................862Exercises ........................................................................................................863
Day 19..................................................................................................................863Quiz ................................................................................................................863Exercises ........................................................................................................864
Day 20..................................................................................................................867Quiz ................................................................................................................867Exercises ........................................................................................................868
Day 21..................................................................................................................873Quiz ................................................................................................................873Exercises ........................................................................................................874
E A Look at Linked Lists 875
The Component Parts of Your Linked List..........................................................876
Index 887
xx Sams Teach Yourself C++ in 21 Days, Fifth Edition
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xx
About the AuthorsJESSE LIBERTY is the author of numerous books on software development, includingbest-selling titles in C++ and .NET. He is the president of Liberty Associates, Inc.(http://www.LibertyAssociates.com) where he provides custom programming, consulting,and training.
BRADLEY JONES, Microsoft MVP, Visual C++, can be referred to as a webmaster, man-ager, coding grunt, executive editor, and various other things. His time and focus are on anumber of software development sites and channels, including Developer.com,CodeGuru.com, DevX, VBForums, Gamelan, and other Jupitermedia-owned sites. Thisinfluence expands over sites delivering content to over 2.5 million unique developers amonth.
His expertise is in the area of the big CsC, C++, and C#however, his experienceincludes development in PowerBuilder, VB, some Java, ASP, COBOL I/II, and variousother technologies too old to even mention now. He has also been a consultant, analyst,project lead, associate publisher for major technical publishers, and author. His recentauthoring credits include Sams Teach Yourself the C# Language in 21 Days, a 6th editionof Sams Teach Yourself C in 21 Days, and now this edition of Sams Teach Yourself C++in 21 Days. He is also the cofounder and president of the Indianapolis .NET DevelopersAssociation, which is a charter INETA group with membership of over 700. You canoften hear his ramblings on the CodeGuru.com or VBForums.com discussion forums,and he also does the weekly CodeGuru newsletter that goes out to tens of thousands ofdevelopers.
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xxi
Dedication Jesse Liberty: This book is dedicated to the living memory of David Levine.
Bradley Jones: Dedicated to my wife and our future family.
Acknowledgments JESSE LIBERTY: A fifth edition is another chance to acknowledge and to thank thosefolks without whose support and help this book literally would have been impossible.First among them remain Stacey, Robin, and Rachel Liberty.
I must also thank my editors at Sams for being professionals of the highest quality; and Imust especially acknowledge and thank Michael Stephens, Loretta Yates, Songlin Qiu,Seth Kerney, and Karen Annett.
I would like to acknowledge the folks who taught me how to program: Skip Gilbrech andDavid McCune, and those who taught me C++, including Stephen Zagieboylo. I wouldlike to thank the many readers who helped me find errors and typos in the earlier editionsof this book.
Finally, Id like to thank Mrs. Kalish, who taught my sixth-grade class how to do binaryarithmetic in 1965, when neither she nor we knew why.
BRADLEY JONES: I would also like to thank Mark Cashman, David Corbin, Songlin Qiu,and a number of readers from the previous editions.
In this fifth edition, we made an extra effort to ensure accuracy; we focused on honingthe content of this book for technical accuracy with an eye on the latest specifications forthe C++ language. Although we still might have missed something, chances are goodthat we didnt thanks to Mark and David and their close scrutiny of the technical details.
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xxii
We Want to Hear from You!As the reader of this book, you are our most important critic and commentator. We valueyour opinion and want to know what were doing right, what we could do better, whatareas youd like to see us publish in, and any other words of wisdom youre willing topass our way.
As an associate publisher for Sams Publishing, I welcome your comments. You can emailor write me directly to let me know what you did or didnt like about this bookas wellas what we can do to make our books better.
Please note that I cannot help you with technical problems related to the topic of thisbook. We do have a User Services group, however, where I will forward specific technicalquestions related to the book.
When you write, please be sure to include this books title and author as well as yourname, email address, and phone number. I will carefully review your comments andshare them with the author and editors who worked on the book.
Email: [email protected]: Michael Stephens
Associate PublisherSams Publishing800 East 96th StreetIndianapolis, IN 46240 USA
For more information about this book or another Sams Publishing title, visit our websiteat www.samspublishing.com. Type the ISBN (excluding hyphens) or the title of a bookin the Search field to find the page youre looking for.
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xxiii
00 0672327112_fm.qxd 11/19/04 12:52 PM Page xxiv
IntroductionThis book is designed to help you teach yourself how to program with C++. No one canlearn a serious programming language in just three weeks, but each of the lessons in thisbook has been designed so that you can read the entire lesson in just a few hours on asingle day.
In just 21 days, youll learn about such fundamentals as managing input and output,loops and arrays, object-oriented programming, templates, and creating C++ applicationsall in well-structured and easy-to-follow lessons. Lessons provide samplelistingscomplete with sample output and an analysis of the codeto illustrate the top-ics of the day.
To help you become more proficient, each lesson ends with a set of common questionsand answers, a quiz, and exercises. You can check your progress by examining the quizand exercise answers provided in Appendix D, Answers.
Who Should Read This BookYou dont 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 con-cepts involved with programming C++. Youll find the numerous examples of syntax anddetailed analysis of code an excellent guide as you begin your journey into this reward-ing environment. Whether you are just beginning or already have some experience pro-gramming, you will find that this books clear organization makes learning C++ fast andeasy.
Conventions Used in This Book
These boxes provide additional information related to material you justread.
NOTE
These boxes highlight information that can make your C++ programmingmore efficient and effective.
TIP
01 0672327112_intro.qxd 11/19/04 12:24 PM Page 1
2 Sams Teach Yourself C++ in 21 Days
This book uses various typefaces to help you distinguish C++ code from regular English.Actual C++ code is typeset in a special monospace font. Placeholderswords or charac-ters temporarily used to represent the real words or characters you would type in codeare 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 unnumberedline in a listing, youll know that the unnumbered line is really a continuation of the pre-ceding numbered code line (some code lines are too long for the width of the book). Inthis case, you should type the two lines as one; do not divide them.
Sample Code for This BookThe sample code described throughout this book and Appendix D, Answers, are avail-able on the Sams website at http://www.samspublishing.com. Enter this books ISBN(without the hyphens) in the Search box and click Search. When the books title is dis-played, click the title to go to a page where you can download the code and Appendix D.
FAQ
What do FAQs do?
Answer: These Frequently Asked Questions provide greater insight into the use of the languageand clarify potential areas of confusion.
These boxes provide clear definitions of essential terms.
DO use the Do/Dont boxes to find aquick summary of a fundamental princi-ple in a lesson.
DONT overlook the useful informationoffered in these boxes.
DO DONT
These focus your attention on problems or side effects that can occur in spe-cific situations.
CAUTION
01 0672327112_intro.qxd 11/19/04 12:24 PM Page 2
At a GlanceAs you prepare for your first week of learning how to pro-gram in C++, you will need a few things: a compiler, an edi-tor, and this book. If you dont have a C++ compiler and aneditor, you can still use this book, but you wont get as muchout of it as you would if you were to do the exercises.
The best way to learn to program is by writing programs! Atthe end of each day, you will find a workshop containing aquiz and some exercises. Be certain to take the time to answerall the questions, and to evaluate your work as objectively asyou can. The later lessons build on what you learn in the ear-lier days, so be certain you fully understand the materialbefore moving on.
A Note to C ProgrammersThe material in the first five days will be familiar to you;however, there are a few minor differences if you want to fol-low the C++ standards. Be certain to skim the material and todo the exercises, to ensure you are fully up to speed beforegoing on to Day 6, Understanding Object-OrientedProgramming.
Where You Are GoingThe first week covers the material you need to get startedwith programming in general, and with C++ in particular. OnDay 1, Getting Started, and Day 2, The Anatomy of a C++Program, you will be introduced to the basic concepts ofprogramming and program flow. On Day 3, Working withVariables and Constants, you will learn about variables and
WEEK 1 1
2
3
4
5
6
7
02 0672327112_w1_aag.qxd 11/19/04 12:25 PM Page 3
4 Week 1
constants and how to use data in your programs. On Day 4, Creating Expressions andStatements, you will learn how programs branch based on the data provided and theconditions encountered when the program is running. On Day 5, Organizing intoFunctions, you will learn what functions are and how to use them, and on Day 6 youwill learn about classes and objects. On Day 7, More on Program Flow, you will learnmore about program flow, and by the end of the first week, you will be writing realobject-oriented programs.
02 0672327112_w1_aag.qxd 11/19/04 12:25 PM Page 4
DAY 1
WEEK 1
Getting StartedWelcome to Sams Teach Yourself C++ in 21 Days! Today, you will get startedon your way to becoming a proficient C++ programmer.
Today, you will learn
Why C++ is a standard in software development
The steps to develop a C++ program
How to enter, compile, and link your first working C++ program
A Brief History of C++Computer languages have undergone dramatic evolution since the first elec-tronic computers were built to assist in artillery trajectory calculations duringWorld War II. Early on, programmers worked with the most primitive computerinstructions: machine language. These instructions were represented by longstrings of ones and zeros. Soon, assemblers were invented to map machineinstructions to human-readable and -manageable mnemonics, such as ADD and MOV.
03 0672327112_ch01.qxd 11/19/04 12:25 PM Page 5
In time, higher-level languages evolved, such as BASIC and COBOL. These languageslet people work with something approximating words and sentences (referred to assource code), such as Let I = 100. These instructions were then translated into machinelanguage by interpreters and compilers.
An interpreter translates and executes a program as it reads it, turning the programinstructions, or source code, directly into actions.
A compiler translates source code into an intermediary form. This step is called compil-ing, and it produces an object file. The compiler then invokes a linker, which combinesthe object file into an executable program.
Because interpreters read the source code as it is written and execute the code on thespot, interpreters can be easier for the programmer to work with. Today, most interpretedprograms are referred to as scripts, and the interpreter itself is often called a scriptengine.
Some languages, such as Visual Basic 6, call the interpreter the runtime library. Otherlanguages, such as the Visual Basic .NET and Java have another component, referred toas a Virtual Machine (VM) or a runtime. The VM or runtime is also an interpreter.However, it is not a source code interpreter that translates human-readable language intocomputer-dependent machine code. Rather, it interprets and executes a compiled computer-independent virtual machine language or intermediary language.
Compilers introduce the extra steps of compiling the source code (which is readable byhumans) into object code (which is readable by machines). This extra step might seeminconvenient, but compiled programs run very fast because the time-consuming task oftranslating the source code into machine language has already been done once, at com-pile time. Because the translation is already done, it is not required when you execute theprogram.
Another advantage of compiled languages such as C++ is that you can distribute the exe-cutable program to people who dont have the compiler. With an interpreted language,you must have the interpreter to run the program.
C++ is typically a compiled language, though there are some C++ interpreters. Likemany compiled languages, C++ has a reputation for producing fast but powerfulprograms.
In fact, for many years, the principal goal of computer programmers was to write shortpieces of code that would execute quickly. Programs needed to be small because memorywas expensive, and needed to be fast because processing power was also expensive. Ascomputers have become smaller, cheaper, and faster, and as the cost of memory has
6 Day 1
03 0672327112_ch01.qxd 11/19/04 12:25 PM Page 6
Getting Started 7
1fallen, these priorities have changed. Today, the cost of a programmers time far out-w
Top Related