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

John paul mueller, jeff cogswell c++ all in one for dummies

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.15 MB, 867 trang )

Start with FREE Cheat Sheets
Cheat Sheets include
• Checklists
• Charts
• Common Instructions
• And Other Good Stuff!
Get Smart at Dummies.com
Dummies.com makes your life easier with 1,000s
of answers on everything from removing wallpaper
to using the latest version of Windows.
Check out our
• Videos
• Illustrated Articles
• Step-by-Step Instructions
Plus, each month you can win valuable prizes by entering
our Dummies.com sweepstakes. *
Want a weekly dose of Dummies? Sign up for Newsletters on
• Digital Photography
• Microsoft Windows & Office
• Personal Finance & Investing
• Health & Wellness
• Computing iPods & Cell Phones
• eBay
• Internet
• Food, Home & Garden
Find out “HOW” at Dummies.com
*Sweepstakes not currently available in all countries; visit Dummies.com for official rules.
Get More and Do More at Dummies.com
®
To access the Cheat Sheet created specifically for this book, go to


www.dummies.com/cheatsheet/cplusplusaio
est. spine=1.72”
by John Paul Mueller and Jeff Cogswell
C++
ALL-IN-ONE
FOR
DUMmIES

2ND EDITION
01_317358-ffirs.indd i01_317358-ffirs.indd i 7/22/09 11:14:29 PM7/22/09 11:14:29 PM
C++ All-in-One For Dummies
®
, 2nd Edition
Published by
Wiley Publishing, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as
permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior
written permission of the Publisher, or authorization through payment of the appropriate per-copy fee
to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978)
646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department,
John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online
at />Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the
Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making Everything

Easier,
and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/
or its af liates in the United States and other countries, and may not be used without written permission.
All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated
with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO
REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF
THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITH-
OUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE
CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES
CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE
UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF
A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE
AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION
OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FUR-
THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR-
MATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE.
FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE
CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care
Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
Library of Congress Control Number: 2009932710
ISBN: 978-0-470-31735-8
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
01_317358-ffirs.indd ii01_317358-ffirs.indd ii 7/22/09 11:14:30 PM7/22/09 11:14:30 PM

Disclaimer: This eBook does not include ancillary media that was packaged with the
printed version of the book.
About the Authors
John Paul Mueller is a freelance author and technical editor. He has writing
in his blood, having produced 83 books and over 300 articles to date. The
topics range from networking to arti cial intelligence and from database
management to heads-down programming. Some of his current books include
a C# design and development guide and a complete reference for LINQ. John
also writes about areas other than programming, such as Exchange Server.
His technical editing skills have helped more than 63 authors re ne the con-
tent of their manuscripts. John has provided technical editing services to
both Data Based Advisor and Coast Compute magazines. He’s also contributed
articles to the following magazines: CIO.com, DevSource, InformIT, Informant,
DevX, SQL Server Professional, Visual C++ Developer, Hard Core Visual Basic,
asp.netPRO, Software Test and Performance, and Visual Basic Developer.
When John isn’t working at the computer, he enjoys spending time in his
workshop crafting wood projects or making candles. On any given afternoon,
you can  nd him working at a lathe or putting the  nishing touches on a
bookcase. He also likes making glycerin soap, which comes in handy for gift
baskets. You can reach John on the Internet at John is
also setting up a Web site and blog at nmuellerbooks.
com/. Feel free to look and make suggestions on how he can improve it.
Jeff Cogswell is an experienced teacher, writer, and software engineer. He
worked 15 years as a professional programmer and software engineer before
leaving that  eld to write and edit full time. He is currently a senior editor
with Ziff Davis Enterprise, writing and editing for DevSource.com and eWEEK.
com. His skills include C++ as well as several other languages and platforms,
such as C# and ASP.NET. In his spare time he enjoys traveling, playing the
guitar, and photography.
01_317358-ffirs.indd iii01_317358-ffirs.indd iii 7/22/09 11:14:30 PM7/22/09 11:14:30 PM

Dedication
This book is dedicated to Dr. Michael Shonfeld and Nurse Barb McPherson,
two special people who may not always get the thanks they deserve. Thank
you so much for your help in returning my beautiful wife to me!
— John Paul Mueller
To my wife Angie, and my son Dylan, with love.
— Jeff Cogswell
01_317358-ffirs.indd iv01_317358-ffirs.indd iv 7/22/09 11:14:30 PM7/22/09 11:14:30 PM
Authors’ Acknowledgments
I really appreciate Jeff having the con dence to work with me on this book.
We’ve known each other for quite some time now and I always enjoy working
with him.
Russ Mullen deserves thanks for his technical edit of this book. He added
greatly to the accuracy and depth of the material that you see here. I appreci-
ated the time he devoted to checking my code for accuracy. As I wrote this
book, I also spent a good deal of time bouncing ideas off Russ, who is a valu-
able aid to any author.
Matt Wagner, my agent, deserves credit for helping me get the contract in the
 rst place and taking care of all the details that most authors don’t consider.
I always appreciate his assistance. It’s good to know that someone wants to
help. Matt also helped me through an extremely dif cult time in my life —
this book is a tribute to the perseverance of us both.
A number of people read all or part of this book to help me re ne the
approach, test the examples, and generally provide input that every reader
wishes they could have. These unpaid volunteers helped in ways too numer-
ous to mention here. I especially appreciate the efforts of Eva Beattie,
Osvaldo Téllez Almirall, and all the others who provided input on C++. I'd
like to thank each person who wrote me with an idea by name, but there are
simply too many.
Finally, I would like to thank Katie Feltman, Susan Pink, Blair Pottenger,

and the rest of the editorial and production staff for their assistance in bring-
ing this book to print. It’s always nice to work with such a great group of
professionals.
— John Paul Mueller
I  rst want to thank John Mueller for taking up such a dif cult task and writ-
ing the second edition of this book, as well as his wife, Rebecca, for staying
strong. Also, another book brings another big thanks to my agent and friend,
Margot Hutchison, for the usual great work. And special thanks to Katie
Feltman and editors Susan Pink and Blair Pottenger for their meticulous
work in making this project reality. Finally, thanks to my wife Angie and my
son Dylan for supporting me in all my projects.
— Jeff Cogswell
01_317358-ffirs.indd v01_317358-ffirs.indd v 7/22/09 11:14:30 PM7/22/09 11:14:30 PM
Publisher’s Acknowledgments
We’re proud of this book; please send us your comments through our online registration form located
at . For other comments, please contact our Customer Care
Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and
Media Development
Project Editor: Susan Pink
(Previous Edition: Pat O’Brien)
Acquisitions Editor: Katie Feltman
Copy Editor: Susan Pink
(Previous Edition: Diana Conover,
Barry Childs-Helton)
Technical Editor: Russ Mullen
Editorial Manager: Jodi Jensen
Media Development Project Manager:
Laura Moss-Hollister

Media Development Assistant Project
Manager: Jenny Swisher
Media Development Associate Producer:
Shawn Patrick
Sr. Editorial Assistant: Cherie Case
Cartoons: Rich Tennant
(www.the5thwave.com)
Composition Services
Project Coordinator: Kristie Rees
Layout and Graphics: Carl Byers, Ronald Terry
Proofreaders: David Faust, Amanda Graham,
John Greenough, Christine Sabooni
Indexer: Broccoli Information Management
Special Help: Marilyn Hummel
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Composition Services
Debbie Stailey, Director of Composition Services
01_317358-ffirs.indd vi01_317358-ffirs.indd vi 7/22/09 11:14:30 PM7/22/09 11:14:30 PM
Contents at a Glance
Introduction 1
Book I: Introducing C++ 7
Chapter 1: Creating a First C++ Program 9
Chapter 2: Storing Data in C++ 29
Chapter 3: Directing Your C++ Program Flow 59

Chapter 4: Dividing Your Work with Functions 83
Chapter 5: Dividing Between Source-Code Files 109
Chapter 6: Referring to Your Data through Pointers 123
Chapter 7: Working with Classes 151
Chapter 8: Using Advanced C++ Features 187
Book II: Understanding Objects and Classes 223
Chapter 1: Planning and Building Objects 225
Chapter 2: Describing Your Program with UML 255
Chapter 3: Structuring Your Classes with UML 275
Chapter 4: Demonstrating Behavior with UML 287
Chapter 5: Modeling Your Programs with UML 305
Chapter 6: Building with Design Patterns 317
Book III: Fixing Problems 347
Chapter 1: Dealing with Bugs 349
Chapter 2: Debugging a Program 361
Chapter 3: Stopping and Inspecting Your Code 373
Chapter 4: Traveling About the Stack 385
Book IV: Advanced Programming 395
Chapter 1: Working with Arrays, Pointers, and References 397
Chapter 2: Creating Data Structures 427
Chapter 3: Constructors, Destructors, and Exceptions 449
Chapter 4: Advanced Class Usage 477
Chapter 5: Creating Classes with Templates 503
Chapter 6: Programming with the Standard Library 535
02_317358-ftoc.indd vii02_317358-ftoc.indd vii 7/22/09 11:15:04 PM7/22/09 11:15:04 PM
Book V: Reading and Writing Files 567
Chapter 1: Filing Information with the Streams Library 569
Chapter 2: Writing with Output Streams 583
Chapter 3: Reading with Input Streams 597
Chapter 4: Building Directories and Contents 609

Chapter 5: Streaming Your Own Classes 619
Book VI: Advanced C++ 631
Chapter 1: Exploring the Standard Library Further 633
Chapter 2: Building Original Templates 651
Chapter 3: Investigating Boost 671
Chapter 4: Boosting up a Step 697
Book VII: Building Applications with Microsoft MFC 713
Chapter 1: Working with the Visual C++ 2008 IDE and Projects 715
Chapter 2: Creating an MFC Dialog Box Project 731
Chapter 3: Creating an MFC SDI Project 747
Chapter 4: Using the Visual C++ 2008 Debugger 769
Chapter 5: Analyzing Your Visual C++ 2008 Code 779
Appendix A: Automating Your
Programs with Makefiles 785
Appendix B: About the CD 797
Index 801
02_317358-ftoc.indd viii02_317358-ftoc.indd viii 7/22/09 11:15:04 PM7/22/09 11:15:04 PM
Table of Contents
Introduction 1
No Experience Necessary 1
Great for Advanced Folks, Too! 1
For All Computers 2
Conventions 2
Organization 3
Icons Galore 4
What’s Next? 5
Book I: Introducing C++ 7
Chapter 1: Creating a First C++ Program . . . . . . . . . . . . . . . . . . . . . . . . . .9
Creating a Project 9
Understanding projects 10

De ning your  rst project 10
Building and executing your  rst application 15
Typing the Code 16
Starting with Main 17
Showing Information 18
Doing some math 22
Tabbing your output 26
Let Your Program Run Away 27
Chapter 2: Storing Data in C++. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
Putting Your Data Places: Variables 30
Creating an integer variable 30
Declaring multiple variables 33
Changing values 33
Setting one variable equal to another 34
Initializing a variable 35
Creating a great name for yourself 36
Manipulating Integer Variables 37
Adding integer variables 38
Subtracting integer variables 41
Multiplying integer variables 43
Dividing integer variables 43
Characters 45
Null character 46
Nonprintable and other cool characters 46
02_317358-ftoc.indd ix02_317358-ftoc.indd ix 7/22/09 11:15:04 PM7/22/09 11:15:04 PM
C++ All-in-One For Dummies, 2nd Edition
x
Strings 48
Getting a part of a string 49
Changing part of a string 51

Adding onto a string 51
Adding two strings 52
Deciding between Conditional Operators 52
Telling the Truth with Boolean Variables 55
Reading from the Console 56
Chapter 3: Directing Your C++ Program Flow. . . . . . . . . . . . . . . . . . . . .59
Doing This or Doing That 60
Evaluating Conditions in C++ 60
Finding the right C++ operators 61
Combining multiple evaluations 62
Including Evaluations in C++ Conditional Statements 63
Deciding what if and also what else 64
Going further with the else and if 65
Repeating Actions with Statements That Loop 67
Looping situations 67
Looping for 68
Looping while 74
Doing while 77
Breaking and continuing 77
Nesting loops 79
Chapter 4: Dividing Your Work with Functions . . . . . . . . . . . . . . . . . . .83
Dividing Your Work 83
Calling a Function 88
Passing a variable 89
Passing multiple variables 90
Writing Your Own Functions 91
Multiple parameters or no parameters 95
Returning nothing 97
Keeping your variables local 98
Forward references and function prototypes 100

Writing two versions of the same function 101
Calling All String Functions 103
Understanding main 105
Chapter 5: Dividing Between Source-Code Files. . . . . . . . . . . . . . . . .109
Creating Multiple Source Files 109
Multiple source  les in CodeBlocks 110
Multiple source  les in other compilers 112
Creating multiple  les 113
02_317358-ftoc.indd x02_317358-ftoc.indd x 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
Table of Contents
xi
Sharing with Header Files 115
Adding the header only once 118
Using brackets or quotes 118
Sharing Variables Among Source Files 119
Using the Mysterious Header Wrappers 121
Chapter 6: Referring to Your Data through Pointers . . . . . . . . . . . . . .123
Heaping and Stacking the Variables 124
Getting a variable’s address 127
Changing a variable by using a pointer 129
Pointing at a string 131
Pointing to something else 133
Tips on pointer variables 134
Dynamically Allocating with new 135
Using new 135
Using an initializer 137
Making new strings 138
Freeing Pointers 139
Passing Pointer Variables to Functions 141
Changing variable values with pointers 141

Modifying string parameters 144
Returning Pointer Variables from Functions 145
Returning a Pointer as a Nonpointer 148
Passing by Reference 149
Remembering the Rules 150
Chapter 7: Working with Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151
Understanding Objects and Classes 151
Classifying classes and objects 153
Describing member functions and data 154
Implementing a class 156
Separating member function code 160
The parts of a class 163
Working with a Class 164
Accessing members 164
Using classes and pointers 167
Passing objects to functions 170
Using const parameters in functions 172
Using the this pointer 173
Overloading member functions 175
Starting and Ending with Constructors and Destructors 178
Starting with constructors 178
Ending with destructors 178
Sampling constructors and destructors 179
Adding parameters to constructors 181
02_317358-ftoc.indd xi02_317358-ftoc.indd xi 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
C++ All-in-One For Dummies, 2nd Edition
xii
Building Hierarchies of Classes 182
Creating a hierarchy in C++ 183
Understanding types of inheritance 184

Chapter 8: Using Advanced C++ Features . . . . . . . . . . . . . . . . . . . . . . .187
Filling Your Code with Comments 187
Converting Types 189
Reading from the Console 195
Understanding Preprocessor Directives 199
Using Constants 207
Using Switch Statements 209
Supercharging enums with Classes 212
Working with Random Numbers 215
Storing Data in Arrays 216
Declaring and accessing an array 217
Arrays of pointers 218
Passing arrays to functions 219
Adding and subtracting pointers 221
Book II: Understanding Objects and Classes 223
Chapter 1: Planning and Building Objects. . . . . . . . . . . . . . . . . . . . . . .225
Recognizing Objects 225
Observing the mailboxes class 227
Observing the mailbox class 229
Finding other objects 230
Encapsulating Objects 230
Building Hierarchies 236
Establishing a hierarchy 236
Protecting members when inheriting 238
Overriding member functions 243
Specializing with polymorphism 245
Getting abstract about things 247
Discovering Classes 248
Engineering your software 249
Finding those pesky classes 252

Chapter 2: Describing Your Program with UML . . . . . . . . . . . . . . . . . .255
Moving Up to UML 255
Modeling with UML 259
Diagramming and designing with UML 259
Building with UML and the Uni ed Process 264
Speaking iteratively 266
Phasing in and out 267
02_317358-ftoc.indd xii02_317358-ftoc.indd xii 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
Table of Contents
xiii
The inception phase 269
The elaboration phase 270
The construction phase 271
The transition phase 272
Moving Forward with UML 273
Chapter 3: Structuring Your Classes with UML . . . . . . . . . . . . . . . . . .275
Drawing Classes 276
Mapping classes with UML 277
Inheriting in UML 280
Aggregating and composing classes 281
Building Components 282
Deploying the Software 285
Chapter 4: Demonstrating Behavior with UML. . . . . . . . . . . . . . . . . . .287
Drawing Objects 287
Casing Out the Use Cases 289
Expanding use cases 291
Matching use cases and requirements 292
Sequence Diagrams 293
Notating sequence diagrams 295
Looping and comparing in sequence diagrams 296

Collaboration Diagrams 299
Activity Diagrams 300
State Diagrams 302
Chapter 5: Modeling Your Programs with UML . . . . . . . . . . . . . . . . . .305
Using UML Goodies 305
Packaging your symbols 305
Notating your diagrams 308
Tagging your symbols 308
Free to Be UML 309
C++ and UML 312
Drawing enumerations 312
Including static members 312
Parameterizing classes with templates 314
Chapter 6: Building with Design Patterns . . . . . . . . . . . . . . . . . . . . . . .317
Introducing a Simple Pattern: the Singleton 318
Watching an Instance with an Observer 322
Observers and the Standard C++ Library 326
Automatically adding an observer 327
Mediating with a Pattern 330
02_317358-ftoc.indd xiii02_317358-ftoc.indd xiii 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
C++ All-in-One For Dummies, 2nd Edition
xiv
Book III: Fixing Problems 347
Chapter 1: Dealing with Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .349
It’s Not a Bug, It’s a Feature! 349
Make Your Programming Features Look Like Features 351
Anticipating (Almost) Everything 352
Avoiding Mistakes, Plain and Simple 359
Chapter 2: Debugging a Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .361
Programming with Debuggers 361

Running the debugger 363
Recognizing the parts of the CodeBlocks debugger 369
Debugging with Different Tools 371
Standard debuggers 371
Chapter 3: Stopping and Inspecting Your Code . . . . . . . . . . . . . . . . . .373
Setting and Disabling Breakpoints 374
Setting a breakpoint in CodeBlocks 375
Enabling and disabling breakpoints 376
Watching, Inspecting, and Changing Variables 378
Watching the local variables 380
Watching other variables 382
Chapter 4: Traveling About the Stack. . . . . . . . . . . . . . . . . . . . . . . . . . .385
Stacking Your Data 385
Moving about the stack 386
Storing local variables 388
Debugging with Advanced Features 390
Viewing threads 390
Tracing through assembly code 391
Book IV: Advanced Programming 395
Chapter 1: Working with Arrays, Pointers, and References . . . . . . .397
Building Up Arrays 397
Declaring arrays 398
Arrays and pointers 400
Using multidimensional arrays 403
Arrays and command-line parameters 406
Allocating an array on the heap 407
Storing arrays of pointers and arrays of arrays 409
Building constant arrays 411
02_317358-ftoc.indd xiv02_317358-ftoc.indd xiv 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
Table of Contents

xv
Pointing with Pointers 413
Becoming horribly complex 413
Pointers to functions 418
Pointing a variable to a member function 419
Pointing to static member functions 422
Referring to References 422
Reference variables 423
Returning a reference from a function 424
Chapter 2: Creating Data Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . .427
Working with Data 427
The great variable roundup 427
Expressing variables from either side 429
Casting a spell on your data 431
Casting safely with C++ 433
Dynamically casting with dynamic_cast 433
Statically casting with static_cast 437
Structuring Your Data 438
Structures as component data types 439
Equating structures 440
Returning compound data types 441
Naming Your Space 442
Using variables and part of a namespace 445
Chapter 3: Constructors, Destructors, and Exceptions . . . . . . . . . . . .449
Constructing and Destructing Objects 449
Overloading constructors 450
Initializing members 451
Adding a default constructor 455
Functional constructors 458
Calling one constructor from another 460

Copying instances with copy constructors 461
When constructors go bad: failable constructors? 464
Destroying your instances 465
Virtually inheriting destructors 466
Programming the Exceptions to the Rule 469
Throwing direct instances 472
Catching any exception 473
Rethrowing an exception 474
Chapter 4: Advanced Class Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . .477
Inherently Inheriting Correctly 477
Morphing your inheritance 477
Adjusting access 480
Returning something different, virtually speaking 482
Multiple inheritance 486
02_317358-ftoc.indd xv02_317358-ftoc.indd xv 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
C++ All-in-One For Dummies, 2nd Edition
xvi
Virtual inheritance 489
Friend classes and functions 492
Using Classes and Types within Classes 493
Nesting a class 494
Types within classes 499
Chapter 5: Creating Classes with Templates . . . . . . . . . . . . . . . . . . . .503
Templatizing a Class 503
Separating a template from the function code 510
Including static members in a template 512
Parameterizing a Template 514
Putting different types in the parameter 514
Including multiple parameters 518
Typede ng a Template 521

Deriving Templates 522
Deriving classes from a class template 522
Deriving a class template from a class 524
Deriving a class template from a class template 525
Templatizing a Function 528
Overloading and function templates 530
Templatizing a member function 533
Chapter 6: Programming with the Standard Library . . . . . . . . . . . . . .535
Architecting the Standard Library 536
Containing Your Classes 536
Storing in a vector 536
Mapping your data 538
Containing instances, pointers, or references 539
Comparing instances 543
Iterating through a container 547
A map of pairs in your hand 551
The Great Container Showdown 551
Associating and storing with a set 552
Unionizing and intersecting sets 554
Listing with list 557
Stacking the deque 561
Waiting in line with stacks and queues 562
Copying Containers 564
Book V: Reading and Writing Files 567
Chapter 1: Filing Information with the Streams Library . . . . . . . . . . .569
Seeing a Need for Streams 570
Programming with the Streams Library 571
Getting the right header  le 572
Opening a  le 573
02_317358-ftoc.indd xvi02_317358-ftoc.indd xvi 7/22/09 11:15:05 PM7/22/09 11:15:05 PM

Table of Contents
xvii
Handling Errors When Opening a File 576
Flagging the ios Flags 578
Chapter 2: Writing with Output Streams . . . . . . . . . . . . . . . . . . . . . . . .583
Inserting with the << Operator 583
Formatting Your Output 585
Formatting with  ags 586
Specifying a precision 590
Setting the width and creating  elds 592
Chapter 3: Reading with Input Streams . . . . . . . . . . . . . . . . . . . . . . . . .597
Extracting with Operators 597
Encountering the End of File 599
Reading Various Types 604
Reading Formatted Input 607
Chapter 4: Building Directories and Contents . . . . . . . . . . . . . . . . . . .609
Manipulating Directories 610
Creating a directory 610
Deleting a directory 611
Getting the Contents of a Directory 611
Copying Files 614
Moving and Renaming Files and Directories 616
Chapter 5: Streaming Your Own Classes. . . . . . . . . . . . . . . . . . . . . . . .619
Streaming a Class for Text Formatting 620
Manipulating a Stream 623
What’s a manipulator? 623
Writing your own manipulator 626
Book VI: Advanced C++ 631
Chapter 1: Exploring the Standard Library Further. . . . . . . . . . . . . . . .633
Considering the Standard Library Categories 634

Containers 635
Iterators 635
Algorithms 636
Functors 637
Utilities 639
Adaptors 639
Allocators 639
Parsing Strings Using a Hash 640
Obtaining Information Using a Random Access Iterator 643
Locating Values Using the Find Algorithm 645
Using the Random Number Generator 647
02_317358-ftoc.indd xvii02_317358-ftoc.indd xvii 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
C++ All-in-One For Dummies, 2nd Edition
xviii
Performing Comparisons Using min and max 648
Working with Temporary Buffers 649
Chapter 2: Building Original Templates. . . . . . . . . . . . . . . . . . . . . . . . .651
Deciding When to Create a Template 652
De ning the Elements of a Good Template 653
Creating a Basic Math Template 655
Building a Structure Template 656
Developing a Class Template 659
Considering Template Specialization 662
Creating a Template Library 664
De ning the library project 664
Con guring the library project 666
Coding the library 667
Using Your Template Library 669
Chapter 3: Investigating Boost. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .671
Understanding Boost 672

Boost features 672
Licensing 673
Paid support 673
Obtaining and Installing Boost for CodeBlocks 673
Unpacking Boost 674
Building the libraries 675
Building the Boost tools 678
Using Boost Jam 680
Using Boost Build 682
Using Regression 685
Using Inspect 685
Understanding BoostBook 687
Using QuickBook 689
Using bcp 690
Using Wave 692
Building Your First Boost Application Using Date Time 693
Chapter 4: Boosting up a Step . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .697
Parsing Strings Using RegEx 698
Adding the RegEx library 699
Creating the RegEx code 700
Breaking Strings into Tokens Using Tokenizer 702
Performing Numeric Conversion 703
Creating Improved Loops Using Foreach 706
Accessing the Operating System Using Filesystem 708
02_317358-ftoc.indd xviii02_317358-ftoc.indd xviii 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
Table of Contents
xix
Book VII: Building Applications with Microsoft MFC 713
Chapter 1: Working with the Visual C++ 2008 IDE and Projects . . . .715
Understanding the Project Types 716

Creating a New Win32 Console Application 717
De ning the project 717
Adding code 719
Running the application 720
Writing Code Faster 721
Obtaining coding help 721
Working with IntelliSense 722
Viewing Your Project in Solution Explorer 723
Using the Standard Toolbars 724
Changing Application Properties 725
Modifying the IDE Appearance 726
Changing toolbars and menus 726
Modifying windows 728
Chapter 2: Creating an MFC Dialog Box Project . . . . . . . . . . . . . . . . .731
Understanding the MFC Dialog Box Project 731
Creating the MFC Dialog Box Project 732
Adding Components and Controls 738
Adding the component or control 738
Creating variables to use in your code 741
De ning methods to react to control events 742
De ning the Dialog Box Code 743
Understanding the Essential Windows 745
Working with Class View 745
Modifying the Toolbox 746
Chapter 3: Creating an MFC SDI Project . . . . . . . . . . . . . . . . . . . . . . . .747
Understanding the MFC SDI Project 747
Creating the MFC SDI Project 749
Understanding the Document/View Architecture 756
Adding Code to Your SDI Project 757
An overview of the essential application  les 757

Locating Microsoft speci ed suggested changes 759
Making resource changes 760
Considering the help  le 763
Registering and unregistering the application 765
Seeing the Text Editor Project in Action 766
02_317358-ftoc.indd xix02_317358-ftoc.indd xix 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
C++ All-in-One For Dummies, 2nd Edition
xx
Chapter 4: Using the Visual C++ 2008 Debugger. . . . . . . . . . . . . . . . . .769
A Quick Look at the Error Application 770
Starting Your Application in Debugging Mode 771
Creating the proper build 772
Setting breakpoints 772
Viewing your breakpoints 774
Starting the debugger 775
Working with the Debugging Windows 775
Viewing the focus variables using the Autos window 775
Viewing all of the variables in a method
using the Locals window 777
Screening speci c variables using the Watch 1 window 777
Working with the Call Stack window 778
Chapter 5: Analyzing Your Visual C++ 2008 Code. . . . . . . . . . . . . . . . .779
Using Performance Wizard 779
Pro ling the Code 781
Appendix A: Automating Your
Programs with Makefiles 785
Compiling and Linking 785
Automating Your Work 787
Implying with Inference Rules 788
Using rules that depend on other rules 790

Making speci c items 791
Depending on multiple  les 791
Compiling and linking with make 793
Cleaning up and making it all 793
Using macros 794
Getting the most out of Make les 795
Appendix B: About the CD 797
System Requirements 797
Using the CD 798
What You’ll Find on the CD 798
CodeBlocks Compiler 799
Author-created material 799
Troubleshooting 799
Customer Care 800
Index 801
02_317358-ftoc.indd xx02_317358-ftoc.indd xx 7/22/09 11:15:05 PM7/22/09 11:15:05 PM
Introduction
C
++ is the language of the millennium. Why is C++ so
popular?
✦ It’s powerful. You can write almost any program in it.
✦ It’s fast, and it’s fully compiled. That’s a good thing.
✦ It’s easy to use — if you have this book.
✦ It’s object-oriented. If you’re not sure what that is, don’t worry. You can
find out about it by reading this very book you’re holding.
✦ It’s portable. Versions are available for nearly every computer.
✦ It’s standardized. The American National Standards Institute and the
International Standards Organization both approve an official version.
✦ It’s popular. More people are using C++ because so many other people
use it.

Sure, some people criticize C++. But most of these people don’t truly under-
stand C++ or are just having a bad day. Or both.
No Experience Necessary
This book is not a big rant about C++. Rather, it’s a hands-on, roll-up-your-
sleeves book, where you will truly learn C++.
At the very beginning, we start you out from square one. We don’t assume
any programming experience whatsoever. Everybody has to start some-
where. You can start here. Not to brag, but you are in the hands of highly
successful C++ users who have shown thousands of people how to program,
many of whom started out from square one.
Great for Advanced Folks, Too!
You already know C++? This book is great for you, too, because although we
start discussing C++ from the beginning, we go all the way through it.
Want to know how to derive a nontemplatized class from a class template?
Check out Minibook IV, Chapter 5.
03_317358-intro.indd 103_317358-intro.indd 1 7/22/09 11:15:24 PM7/22/09 11:15:24 PM
2
For All Computers
Want to see how to create an observer pattern in C++? See Minibook II,
Chapter 6.
Want to find out the difference between deque and vector in the C++
Standard Library? Look at Minibook IV, Chapter 6.
Want to know how to make a class persistent? Minibook V, Chapter 5.
Want to know about the Boost library, the library that has added more to
the Standard Template Library (STL) than just about any other source?
Check out Minibook VI, Chapters 3 and 4. If you use C++ and don’t use Boost,
you’re really missing out!
For All Computers
Although one of the minibooks in C++ All-in-For Dummies, 2nd Edition is
devoted to Microsoft-specific topics (Minibook VII on Visual Studio 6.0 and

MFC), the rest of the book is for C++ in general. C++ is now standardized, and
you can use the information in this book for many different platforms. We
wrote the samples on Microsoft Windows. But for most samples, we used a
compiler called CodeBlocks that runs on almost every computer (Windows,
Linux, and Macintosh). It doesn’t matter which computer you’re using!
All the code in this book, except that in Minibook VII, has been tested on
both Windows and Linux. (Don’t let the Windows screenshots fool you;
CodeBlocks works great on just about any platform.) Even though we didn’t
have a Macintosh available for testing at the time of writing, we’re sure that
the examples will also work fine in the Macintosh environment if you use the
CodeBlocks compiler as described in the book.
Conventions
As a guy who is about to head off to a convention, we thought it would be
appropriate to share with you some tidbits about the conventions in this
book. However, this time we’re talking about the text format.
✦ When you see something in monofont, it’s a computer word that you
type into the computer or read on a computer screen. If we discuss a com-
puter term but it’s not a word that you type into the computer, it is in
the usual font. You also see monofont for URLs and e-mail addresses.
✦ When you see something in bold, you can type it into the computer.
✦ When you see a word in italics, it’s new and we explain its meaning.
✦ When code is on a single line, it looks like this:
MyClass.IsCool();
03_317358-intro.indd 203_317358-intro.indd 2 7/22/09 11:15:24 PM7/22/09 11:15:24 PM
3
Organization
✦ When code appears on multiple lines, it looks like this:
MyClass.IsCool();
AndSo.IsYours();
✦ Lengthy program listings have a header and a listing number. These are

entire programs you can type, and they should run as-is. However, you
save time and effort by using the code supplied as part of the book’s CD.
The CD also contains a full copy of the Windows version of CodeBlocks.
Organization
This book is divided into seven minibooks. Each one covers a separate,
broad topic, with chapters devoted to individual subtopics.
You can either read this book cover to cover or you can look topics up and
treat the book as a reference guide — whichever works best for you. Keep it
on your shelf and have it ready to grab when you need to look something up.
Here are the seven minibooks and what they cover:
✦ Minibook I, Introducing C++: Here, we start at the very beginning,
showing you all you need to know to get up and running with C++. This
is also the minibook that gets you started with CodeBlocks. If you don’t
have a copy of CodeBlocks installed on your system, you definitely want
to start by reviewing Chapter 1.
✦ Minibook II, Understanding Objects and Classes: In this minibook, we
present all the latest information about object-oriented programming
and how to use various diagrams to design your programs. Advanced
readers should especially appreciate this minibook because we cover
such topics as UML and design patterns. But beginners should be able
to understand it, too, and find out how to get up to speed with the best
software engineering ideas around.
✦ Minibook III, Fixing Problems: Here, we show you how to debug your
programs by using a special program called a debugger. If you’re a
beginner, this minibook gets you started on fixing the problems in your
code. If you’re advanced, you can appreciate how we use the debug-
ger supplied with CodeBlocks to locate any problems your application
might have.
✦ Minibook IV, Advanced Programming: In this minibook, we move
through advanced C++ topics. After reading Minibook IV, the beginners

become intermediate or advanced programmers, and the intermediate
and advanced programmers can master the C++ language.
✦ Minibook V, Reading and Writing Files: Yes, this entire minibook is
devoted to the issues of reading and writing files. In this book, we cover
stream programming, which is a special way C++ treats files.
03_317358-intro.indd 303_317358-intro.indd 3 7/22/09 11:15:24 PM7/22/09 11:15:24 PM

×