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

professional c++ programming (programmer to programmer)

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 (11.76 MB, 865 trang )

TeA
M
YYe
PG
Digitally signed by
TeAM YYePG
DN: cn=TeAM
YYePG, c=US,
o=TeAM YYePG,
ou=TeAM YYePG,
email=yyepg@ms
n.com
Reason: I attest to
the accuracy and
integrity of this
document
Date: 2005.02.23
21:59:53 +08'00'
Professional C++
Nicholas A. Solter
Scott J. Kleper
01_574841 ffirs.qxd 12/15/04 3:38 PM Page i
Professional C++
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2005 by Wiley Publishing, Inc. All rights reserved.
Published simultaneously in Canada
Printed in the United States of America


10 9 8 7 6 5 4 3 2 1
1B/QV/QR/QV/IN
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 Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256,
(317) 572-3447, fax (317) 572-4355, e-mail:
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 WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CRE-
ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CON-
TAINED 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 NOT THE
AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION
OR WEB SITE 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 WEB SITE 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 United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer and related trade
dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates. 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.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be
available in electronic books.
Solter, Nicholas, 1977-
Professional C++ / Nicholas Solter, Scott Kleper.
p. cm.
Includes index.
ISBN 0-7645-7484-1 (paper/website)
1. C++ (Computer program language) I. Kleper, Scott, 1977- II. Title.
QA76.73.C153S665 2005
005.13'3 dc22
2004027959
01_574841 ffirs.qxd 12/15/04 3:38 PM Page ii
Dedications
To Sonja, for her unconditional love and support, and to my son Kai, whose frequent interruptions
reminded me what’s important in life.
—Nicholas A. Solter
To Marni, whose unpredictable cuteness brightens every day.
—Scott J. Kleper
Acknowledgments
We owe a debt of gratitude to the many people who have made this book possible. We’d like to thank
David Fugate of Waterside Productions for all of his advice and guidance, and Robert Elliot at Wiley for
giving two unknown authors the opportunity to tell the C++ story in a new way. This book would not
have turned out nearly as well as it did without the assistance of our development editor, Adaobi Obi
Tulton. Thanks also to Kathryn Malm Bourgoine for her editorial assistance. The photo on the cover,
which artfully minimized our nerdiness, was taken by Adam Tow.
We also want to thank all of the coworkers and teachers who have encouraged us to code the right way
over the years. In particular, thanks to Mike Hanson, Maggie Johnson, Adam Nash, Nick Parlante, Bob
Plummer, Eric Roberts, Mehran Sahami, Bill Walker, Dan Walkowski, Patrick Young, and Julie Zelenski.
Our eternal thanks to Jerry Cain, who not only taught us C++ originally, but also served as technical edi-
tor, religiously analyzing the code in this book as though it were one of our final exams.

Thanks also to the following people, who reviewed one or more chapters: Rob Baesman, Aaron Bradley,
Elaine Cheung, Marni Kleper, Toli Kuznets, Akshay Rangnekar, Eltefaat Shokri, Aletha Solter, Ken Solter,
and Sonja Solter. Any remaining errors are, of course, our own. We’d like to thank our families for their
patience and support.
Finally, we’d like to thank you, our readers, for trying out our approach to professional C++
development.
01_574841 ffirs.qxd 12/15/04 3:38 PM Page iii
Credits
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Publisher
Joseph B. Wikert
Executive Editor
Robert Elliott
Editorial Manager
Kathryn Malm Bourgoine
Senior Production Editor
Geraldine Fahey
Senior Development Editor
Adaobi Obi Tulton
Production Editor
Felicia Robinson
Media Development Specialist
Richard Graves
Technical Editor
Jerry Cain
Text Design & Composition
Wiley Composition Services
Cover Photographer
Adam Tow

Author Bios
Nicholas A. Solter studied computer science at Stanford University, where he earned bachelor of science
and master of science degrees, with a concentration in systems. While a student, he worked as a teaching
assistant for several classes ranging from introductory computer science for nonmajors to an upper-
division course on group projects and software engineering.
Now a software engineer at Sun Microsystems, Nick programs primarily in C and C++ in his work on
high-availability software. His previous work experience includes several stints in the computer game
industry. At Digital Media International, he was the lead programmer on the multimedia educational
game, The Land Before Time Math Adventure. During an internship at Electronic Arts, he helped develop
the Course Architect 2000 golf course–editing tool for the Tiger Woods PGA Tour 2000 game.
In addition to his industry experience, Nick taught C++ for one year as an adjunct professor of computer
science at Fullerton College. When not working, Nick enjoys reading, playing basketball, taking care of
his son Kai, and spending time with his family.
Scott J. Kleper began his programming career in elementary school, writing adventure games in BASIC
for the Tandy TRS-80. As the resident Mac geek at his high school, Scott moved to higher-level languages
and released several award-winning shareware applications.
Scott attended Stanford University, where he obtained bachelor of science and master of science degrees
in computer science, with a concentration in human-computer interaction. While in college, Scott served
as a teaching assistant for classes involving introductory programming, object-oriented design, data
structures, GUI frameworks, group projects, and Internet programming.
Since graduating, Scott has served as a lead engineer on the founding teams of several companies and is
currently a senior software engineer at Reactivity, Inc. Outside of work, Scott is a compulsive online
shopper, an avid reader, and an awful guitarist.
01_574841 ffirs.qxd 12/15/04 3:38 PM Page iv
Contents
Introduction xxi
Who This Book Is For xxi
What This Book Covers xxi
How This Book Is Structured xxii
What You Need to Use This Book xxiii

Conventions xxiii
Source Code xxiv
Errata xxiv
p2p.wrox.com xxiv
Part I: Introduction to Professional C++
Chapter 1: A Crash Course in C++ 1
The Basics of C++ 1
The Obligatory Hello, World 2
Namespaces 4
Variables 6
Operators 8
Types 10
Conditionals 12
Loops 14
Arrays 15
Functions 16
Those Are the Basics 17
Diving Deeper into C++ 18
Pointers and Dynamic Memory 18
Strings in C++ 21
References 23
Exceptions 23
The Many Uses of const 25
C++ as an Object-Oriented Language 26
Declaring a Class 26
Your First Useful C++ Program 29
An Employee Records System 29
The Employee Class 29
02_574841 ftoc.qxd 12/15/04 3:39 PM Page v
vi

Contents
The Database Class 34
The User Interface 38
Evaluating the Program 41
Summary 41
Chapter 2: Designing Professional C++ Programs 43
What Is Programming Design? 44
The Importance of Programming Design 44
What’s Different about C++ Design? 46
Two Rules for C++ Design 47
Abstraction 47
Reuse 49
Designing a Chess Program 50
Requirements 51
Design Steps 51
Summary 56
Chapter 3: Designing with Objects 57
An Object-Oriented View of the World 57
Am I Thinking Procedurally? 57
The Object-Oriented Philosophy 58
Living in a World of Objects 61
Object Relationships 63
Abstraction 73
Summary 76
Chapter 4: Designing with Libraries and Patterns 77
Reusing Code 77
A Note on Terminology 78
Deciding Whether or Not to Reuse Code 78
Strategies for Reusing Code 81
Bundling Third-Party Applications 85

Open-Source Libraries 86
The C++ Standard Library 87
Designing with Patterns and Techniques 101
Design Techniques 101
Design Patterns 102
Summary 103
02_574841 ftoc.qxd 12/15/04 3:39 PM Page vi
vii
Contents
Chapter 5: Designing for Reuse 105
The Reuse Philosophy 106
How to Design Reusable Code 106
Use Abstraction 107
Structure Your Code for Optimal Reuse 108
Design Usable Interfaces 112
Reconciling Generality and Ease of Use 117
Summary 118
Chapter 6: Maximizing Software-Engineering Methods 119
The Need for Process 119
Software Life-Cycle Models 120
The Stagewise and Waterfall Models 121
The Spiral Method 123
The Rational Unified Process 126
Software-Engineering Methodologies 127
Extreme Programming (XP) 128
Software Triage 132
Building Your Own Process and Methodology 132
Be Open to New Ideas 132
Bring New Ideas to the Table 132
Recognize What Works and What Doesn’t Work 133

Don’t Be a Renegade 133
Summary 133
Part II: C++ Coding the Professional Way
Chapter 7: Coding with Style 135
The Importance of Looking Good 135
Thinking Ahead 135
Keeping It Clear 136
Elements of Good Style 136
Documenting Your Code 136
Reasons to Write Comments 136
Commenting Styles 140
Comments in This Book 145
02_574841 ftoc.qxd 12/15/04 3:39 PM Page vii
viii
Contents
Decomposition 145
Decomposition through Refactoring 147
Decomposition by Design 147
Decomposition in This Book 148
Naming 148
Choosing a Good Name 148
Naming Conventions 148
Using Language Features with Style 151
Use Constants 151
Take Advantage of const Variables 151
Use References Instead of Pointers 151
Use Custom Exceptions 152
Formatting 152
The Curly Brace Alignment Debate 153
Coming to Blows over Spaces and Parentheses 154

Spaces and Tabs 154
Stylistic Challenges 155
Summary 155
Chapter 8: Gaining Proficiency with Classes and Objects 157
Introducing the Spreadsheet Example 157
Writing Classes 158
Class Definitions 158
Defining Methods 161
Using Objects 164
Object Life Cycles 165
Object Creation 165
Object Destruction 176
Assigning to Objects 177
Distinguishing Copying from Assignment 180
Summary 182
Chapter 9: Mastering Classes and Objects 183
Dynamic Memory Allocation in Objects 183
The Spreadsheet Class 184
Freeing Memory with Destructors 186
Handling Copying and Assignment 186
Different Kinds of Data Members 194
Static Data Members 195
Const Data Members 196
Reference Data Members 198
Const Reference Data Members 199
02_574841 ftoc.qxd 12/15/04 3:39 PM Page viii
ix
Contents
More about Methods 199
Static Methods 199

Const Methods 200
Method Overloading 202
Default Parameters 203
Inline Methods 204
Nested Classes 206
Friends 208
Operator Overloading 209
Implementing Addition 209
Overloading Arithmetic Operators 212
Overloading Comparison Operators 215
Building Types with Operator Overloading 216
Pointers to Methods and Members 217
Building Abstract Classes 218
Using Interface and Implementation Classes 218
Summary 221
Chapter 10: Discovering Inheritance Techniques 223
Building Classes with Inheritance 224
Extending Classes 224
Overriding Methods 227
Inheritance for Reuse 230
The WeatherPrediction Class 230
Adding Functionality in a Subclass 231
Replacing Functionality in a Subclass 233
Respect Your Parents 234
Parent Constructors 234
Parent Destructors 235
Referring to Parent Data 237
Casting Up and Down 239
Inheritance for Polymorphism 240
Return of the Spreadsheet 240

Designing the Polymorphic Spreadsheet Cell 241
The Spreadsheet Cell Base Class 242
The Individual Subclasses 243
Leveraging Polymorphism 245
Future Considerations 246
Multiple Inheritance 248
Inheriting from Multiple Classes 248
Naming Collisions and Ambiguous Base Classes 249
02_574841 ftoc.qxd 12/15/04 3:39 PM Page ix
x
Contents
Interesting and Obscure Inheritance Issues 253
Changing the Overridden Method’s Characteristics 253
Special Cases in Overriding Methods 256
Copy Constructors and the Equals Operator 263
The Truth about Virtual 264
Runtime Type Facilities 267
Non-Public Inheritance 269
Virtual Base Classes 269
Summary 270
Chapter 11: Writing Generic Code with Templates 271
Overview of Templates 272
Class Templates 273
Writing a Class Template 273
How the Compiler Processes Templates 280
Distributing Template Code between Files 281
Template Parameters 282
Method Templates 285
Template Class Specialization 290
Subclassing Template Classes 293

Inheritance versus Specialization 295
Function Templates 295
Function Template Specialization 296
Function Template Overloading 297
Friend Function Templates of Class Templates 298
Advanced Templates 299
More about Template Parameters 299
Template Class Partial Specialization 307
Emulating Function Partial Specialization with Overloading 313
Template Recursion 314
Summary 322
Chapter 12: Understanding C++ Quirks and Oddities 323
References 323
Reference Variables 324
Reference Data Members 326
Reference Parameters 326
Reference Return Values 327
Deciding between References and Pointers 327
02_574841 ftoc.qxd 12/15/04 3:39 PM Page x
xi
Contents
Keyword Confusion 330
The const Keyword 330
The static Keyword 333
Order of Initialization of Nonlocal Variables 336
Types and Casts 337
typedefs 337
Casts 338
Scope Resolution 343
Header Files 343

C Utilities 345
Variable-Length Argument Lists 345
Preprocessor Macros 347
Summary 348
Part III: Mastering Advanced Features of C++
Chapter 13: Effective Memory Management 349
Working with Dynamic Memory 349
How to Picture Memory 350
Allocation and Deallocation 351
Arrays 353
Working with Pointers 360
Array-Pointer Duality 362
Arrays Are Pointers! 363
Not All Pointers Are Arrays! 364
Dynamic Strings 365
C-Style Strings 365
String Literals 366
The C++ string Class 367
Low-Level Memory Operations 369
Pointer Arithmetic 369
Custom Memory Management 370
Garbage Collection 370
Object Pools 371
Function Pointers 372
Common Memory Pitfalls 374
Underallocating Strings 374
Memory Leaks 374
Double-Deleting and Invalid Pointers 377
Accessing Out-of-Bounds Memory 378
Summary 378

02_574841 ftoc.qxd 12/15/04 3:39 PM Page xi
xii
Contents
Chapter 14: Demystifying C++ I/O 379
Using Streams 379
What Is a Stream, Anyway? 380
Stream Sources and Destinations 380
Output with Streams 380
Input with Streams 384
Input and Output with Objects 389
String Streams 390
File Streams 392
Jumping around with seek() and tell() 392
Linking Streams Together 395
Bidirectional I/O 396
Internationalization 397
Wide Characters 397
Non-Western Character Sets 398
Locales and Facets 398
Summary 400
Chapter 15: Handling Errors 401
Errors and Exceptions 402
What Are Exceptions, Anyway? 402
Why Exceptions in C++ Are a Good Thing 403
Why Exceptions in C++ Are a Bad Thing 404
Our Recommendation 404
Exception Mechanics 404
Throwing and Catching Exceptions 405
Exception Types 406
Throwing and Catching Multiple Exceptions 408

Uncaught Exceptions 411
Throw Lists 412
Exceptions and Polymorphism 416
The Standard Exception Hierarchy 416
Catching Exceptions in a Class Hierarchy 417
Writing Your Own Exception Classes 419
Stack Unwinding and Cleanup 422
Catch, Cleanup, and Rethrow 423
Use Smart Pointers 424
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xii
xiii
Contents
Common Error-Handling Issues 424
Memory Allocation Errors 424
Errors in Constructors 427
Errors in Destructors 428
Putting It All Together 428
Summary 430
Part IV: Ensuring Bug-Free Code
Chapter 16: Overloading C++ Operators 431
Overview of Operator Overloading 432
Why Overload Operators? 432
Limitations to Operator Overloading 432
Choices in Operator Overloading 433
Operators You Shouldn’t Overload 435
Summary of Overloadable Operators 435
Overloading the Arithmetic Operators 438
Overloading Unary Minus and Unary Plus 438
Overloading Increment and Decrement 439
Overloading the Bitwise and Binary Logical Operators 441

Overloading the Insertion and Extraction Operators 441
Overloading the Subscripting Operator 443
Providing Read-Only Access with operator[] 446
Non-Integral Array Indices 447
Overloading the Function Call Operator 448
Overloading the Dereferencing Operators 449
Implementing operator* 451
Implementing operator-> 452
What in the World Is operator->* ? 452
Writing Conversion Operators 453
Ambiguity Problems with Conversion Operators 454
Conversions for Boolean Expressions 455
Overloading the Memory Allocation and Deallocation Operators 457
How new and delete Really Work 457
Overloading operator new and operator delete 459
Overloading operator new and operator delete with Extra Parameters 461
Summary 463
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xiii
xiv
Contents
Chapter 17: Writing Efficient C++ 465
Overview of Performance and Efficiency 465
Two Approaches to Efficiency 466
Two Kinds of Programs 466
Is C++ an Inefficient Language? 466
Language-Level Efficiency 467
Handle Objects Efficiently 467
Don’t Overuse Costly Language Features 471
Use Inline Methods and Functions 472
Design-Level Efficiency 472

Cache as Much as Possible 472
Use Object Pools 473
Use Thread Pools 479
Profiling 479
Profiling Example with gprof 479
Summary 488
Chapter 18: Developing Cross-Platform and Cross-Language Applications 489
Cross-Platform Development 489
Architecture Issues 490
Implementation Issues 492
Platform-Specific Features 493
Cross-Language Development 494
Mixing C and C++ 494
Shifting Paradigms 495
Linking with C Code 498
Mixing Java and C++ with JNI 499
Mixing C++ with Perl and Shell Scripts 501
Mixing C++ with Assembly Code 504
Summary 505
Chapter 19: Becoming Adept at Testing 507
Quality Control 507
Whose Responsibility Is Testing? 508
The Life Cycle of a Bug 508
Bug-Tracking Tools 509
Unit Testing 510
Approaches to Unit Testing 511
The Unit Testing Process 512
Unit Testing in Action 515
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xiv
xv

Contents
Higher-Level Testing 523
Integration Tests 523
System Tests 525
Regression Tests 525
Tips for Successful Testing 526
Summary 526
Chapter 20: Conquering Debugging 527
The Fundamental Law of Debugging 527
Bug Taxonomies 528
Avoiding Bugs 528
Planning for Bugs 528
Error Logging 528
Debug Traces 530
Asserts 540
Debugging Techniques 541
Reproducing Bugs 541
Debugging Reproducible Bugs 542
Debugging Nonreproducible Bugs 543
Debugging Memory Problems 544
Debugging Multithreaded Programs 547
Debugging Example: Article Citations 548
Lessons from the ArticleCitations Example 559
Summary 559
Chapter 21: Delving into the STL: Containers and Iterators 561
Containers Overview 562
Requirements on Elements 562
Exceptions and Error Checking 563
Iterators 564
Sequential Containers 565

Vector 566
The vector<bool> Specialization 583
deque 584
list 584
Container Adapters 588
queue 588
priority_queue 591
stack 594
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xv
xvi
Contents
Associative Containers 595
The pair Utility Class 595
map 596
multimap 604
set 608
multiset 610
Other Containers 611
Arrays as STL Containers 611
Strings as STL Containers 612
Streams as STL Containers 613
bitset 613
Summary 618
Part V: Using Libraries and Patterns
Chapter 22: Mastering STL Algorithms and Function Objects 619
Overview of Algorithms 620
The find() and find_if() Algorithms 620
The accumulate() Algorithms 623
Function Objects 624
Arithmetic Function Objects 624

Comparison Function Objects 625
Logical Function Objects 627
Function Object Adapters 627
Writing Your Own Function Objects 630
Algorithm Details 631
Utility Algorithms 632
Nonmodifying Algorithms 633
Modifying Algorithms 639
Sorting Algorithms 643
Set Algorithms 646
Algorithms and Function Objects Example: Auditing Voter Registrations 648
The Voter Registration Audit Problem Statement 648
The auditVoterRolls() Function 648
The getDuplicates() Function 649
The RemoveNames Functor 650
The NameInList Functor 651
Testing the auditVoterRolls() Function 652
Summary 653
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xvi
xvii
Contents
Chapter 23: Customizing and Extending the STL 655
Allocators 656
Iterator Adapters 656
Reverse Iterators 656
Stream Iterators 657
Insert Iterators 658
Extending the STL 660
Why Extend the STL? 660
Writing an STL Algorithm 660

Writing an STL Container 662
Summary 691
Chapter 24: Exploring Distributed Objects 693
The Appeal of Distributed Computing 693
Distribution for Scalability 693
Distribution for Reliability 694
Distribution for Centrality 694
Distributed Content 695
Distributed versus Networked 695
Distributed Objects 696
Serialization and Marshalling 696
Remote Procedure Calls 700
CORBA 702
Interface Definition Language 702
Implementing the Class 704
Using the Objects 706
XML 709
A Crash Course in XML 709
XML as a Distributed Object Technology 712
Generating and Parsing XML in C++ 712
XML Validation 721
Building a Distributed Object with XML 723
SOAP (Simple Object Access Protocol) 726
Summary 728
Chapter 25: Incorporating Techniques and Frameworks 729
“I Can Never Remember How to . . .” 730
. . . Write a Class 730
. . . Subclass an Existing Class 731
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xvii
xviii

Contents
. . . Throw and Catch Exceptions 732
. . . Read from a File 733
. . . Write to a File 734
. . . Write a Template Class 734
There Must Be a Better Way 736
Smart Pointers with Reference Counting 736
Double Dispatch 741
Mix-In Classes 747
Object-Oriented Frameworks 750
Working with Frameworks 750
The Model-View-Controller Paradigm 750
Summary 752
Chapter 26: Applying Design Patterns 753
The Singleton Pattern 754
Example: A Logging Mechanism 754
Implementation of a Singleton 754
Using a Singleton 759
The Factory Pattern 760
Example: A Car Factory Simulation 760
Implementation of a Factory 762
Using a Factory 764
Other Uses of Factories 766
The Proxy Pattern 766
Example: Hiding Network Connectivity Issues 766
Implementation of a Proxy 767
Using a Proxy 767
The Adapter Pattern 768
Example: Adapting an XML Library 768
Implementation of an Adapter 768

Using an Adapter 772
The Decorator Pattern 773
Example: Defining Styles in Web Pages 773
Implementation of a Decorator 774
Using a Decorator 775
The Chain of Responsibility Pattern 776
Example: Event Handling 776
Implementation of a Chain of Responsibility 777
Using a Chain of Responsibility 778
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xviii
xix
Contents
The Observer Pattern 778
Example: Event Handling 778
Implementation of an Observer 778
Using an Observer 780
Summary 781
Appendix A: C++ Interviews 783
Chapter 1: A Crash Course in C++ 783
Chapter 2: Designing Professional C++ Programs 784
Chapter 3: Designing with Objects 785
Chapter 4: Designing with Libraries and Patterns 786
Chapter 5: Designing for Reuse 787
Chapter 6: Maximizing Software Engineering Methods 787
Chapter 7: Coding with Style 788
Chapters 8 and 9: Classes and Objects 789
Chapter 10: Discovering Inheritance Techniques 792
Chapter 11: Writing Generic Code with Templates 793
Chapter 12: Understanding C++ Quirks and Oddities 793
Chapter 13: Effective Memory Management 794

Chapter 14: Demystifying C++ I/O 795
Chapter 15: Handling Errors 796
Chapter 16: Overloading C++ Operators 796
Chapter 17: Writing Efficient C++ 797
Chapter 18: Developing Cross-Platform and Cross-Language Applications 798
Chapter 19: Becoming Adept at Testing 798
Chapter 20: Conquering Debugging 799
Chapters 21, 22, and 23: The Standard Template Library 799
Chapter 24: Exploring Distributed Objects 800
Chapter 25: Incorporating Techniques and Frameworks 801
Chapter 26: Applying Design Patterns 801
Appendix B: Annotated Bibliography 803
C++ 803
Beginning C++ 803
General C++ 804
I/O Streams 805
The C++ Standard Library 805
C++ Templates 806
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xix
xx
Contents
C 806
Integrating C++ and Other Languages 806
Algorithms and Data Structures 807
Open-Source Software 807
Software-Engineering Methodology 807
Programming Style 808
Computer Architecture 809
Efficiency 809
Testing 809

Debugging 809
Distributed Objects 810
CORBA 810
XML and SOAP 810
Design Patterns 811
Index 813
02_574841 ftoc.qxd 12/15/04 3:39 PM Page xx
xxi
Introduction
For many years, C++ has served as the de facto language for writing fast, powerful, and enterprise-class
object-oriented programs. As popular as C++ has become, the language is surprisingly difficult to grasp
in full. There are simple, but powerful, techniques that professional C++ programmers use that don’t
show up in traditional texts, and there are useful parts of C++ that remain a mystery even to experienced
C++ programmers.
Too often, programming books focus on the syntax of the language instead of its real-world use. The
typical C++ text introduces a major part of the language in each chapter, explaining the syntax and pro-
viding an example. Professional C++ does not follow this pattern. Instead of giving you just the nuts and
bolts of the language with little real-world context, this book will teach you how to use C++ in the real
world. It will show you the little-known features that will make your life easier and the reusable coding
patterns that separate novice programmers from professional programmers.
Who This Book Is For
Even if you have used the language for years, you might still be unfamiliar with the more advanced fea-
tures of C++ or might not be using the full capabilities of the language. Perhaps you write competent
C++ code, but would like to learn more about design in C++ and good programming style. Or maybe
you’re relatively new to C++, but want to learn the “right” way to program from the start. This book will
bring your C++ skills to the professional level.
Because this book focuses on advancing from basic or intermediate knowledge of C++ to becoming a
professional C++ programmer, it assumes some knowledge of the language. Chapter 1 covers the basics
of C++ as a refresher, but it is not a substitute for actual training and use of the language. If you are just
starting with C++, but you have significant experience in C, you should be able to pick up most of what

you need from Chapter 1. In any case, you should have a solid foundation in programming fundamen-
tals. You should know about loops, functions, and variables. You should know how to structure a pro-
gram, and you should be familiar with fundamental techniques like recursion. You should have some
knowledge of common data structures like hash tables and queues, and useful algorithms such as sort-
ing and searching. You don’t need to know about object-oriented programming just yet—that is covered
in Chapter 3.
You will also need to be familiar with the compiler you will be using to develop your code. This book
does not provide directions for using individual compilers. Refer to the documentation that came with
your compiler for a refresher.
What This Book Covers
Professional C++ is an approach to C++ programming that will both increase the quality of your code and
improve your programming efficiency. Professional C++ teaches more than just the syntax and language
features of C++. It also emphasizes programming methodologies, reusable design patterns, and good
03_574841 flast.qxd 12/15/04 3:39 PM Page xxi
xxii
Introduction
programming style. The Professional C++ methodology incorporates the entire software development
process—from designing and writing code to testing, debugging, and working in groups. This approach
will enable you to master the C++ language and its idiosyncrasies, as well as take advantage of its pow-
erful capabilities for large-scale software development.
Imagine someone who has learned all of the syntax of C++ without seeing a single example of its use.
He knows just enough to be dangerous! Without examples, he might assume that all code should go in
the
main() function of the program or that all variables should be global—practices that are generally
not considered hallmarks of good programming.
Professional C++ programmers understand the correct way to use the language, in addition to the syn-
tax. They recognize the importance of good design, the theories of object-oriented programming, and the
best ways to use existing libraries. They have also developed an arsenal of useful code and reusable
ideas.
By reading this book, you will become a professional C++ programmer. You will expand your knowl-

edge of C++ to cover lesser-known and often misunderstood language features. You will gain an appre-
ciation for object-oriented design and acquire top-notch debugging skills. Perhaps most importantly, you
will finish this book armed with a wealth of reusable ideas that can be applied to your actual daily work.
There are many good reasons to make the effort to be a professional C++ programmer, as opposed to a
programmer who knows C++. Understanding the true workings of the language will improve the qual-
ity of your code. Learning about different programming methodologies and processes will help you to
work better with your team. Discovering reusable libraries and common design patterns will improve
your daily efficiency and help you stop reinventing the wheel. All of these lessons will make you a better
programmer and a more valuable employee. While this book can’t guarantee you a promotion, it cer-
tainly won’t hurt!
How This Book Is Structured
This book is made up of six parts.
Part I, “Introduction to Professional C++ Design,” begins with a crash course in C++ basics to ensure a
foundation of C++ knowledge. Following the crash course, Part I explores C++ design methodologies.
You will read about the importance of design, the object-oriented methodology, the use of libraries and
patterns, the importance of code reuse, and the engineering practices being used by programming orga-
nizations today.
Part II, “Coding C++ the Professional Way,” provides a technical tour of C++ from the Professional
point-of-view. You will read about how to write readable C++ code, how to create reusable classes, and
how to leverage important language features like inheritance and templates.
Part III, “Mastering Advanced Features of C++,” demonstrates how you can get the most out of C++.
This part of the book exposes the mysteries of C++ and describes how to use some of its more advanced
features. You will read about the unusual and quirky parts of the language, the best ways to manage
memory in C++, techniques for input and output, professional-grade error handling, advanced operator
overloading, how to write efficient C++ code, and how to write cross-language and cross-platform code.
03_574841 flast.qxd 12/15/04 3:39 PM Page xxii
xxiii
Introduction
Part IV, “Ensuring Bug-Free Code,” focuses on writing enterprise-quality software. You’ll read about
software testing concepts, such as unit testing and regression testing. You’ll also read about techniques

used to debug C++ programs.
Part V, “Using Libraries and Patterns,” covers the use of libraries and patterns, which enable you to
write better code with less work. You’ll read about the standard library included with C++, including
advanced topics such as extending the Standard Library. You’ll also read about distributed objects,
reusable C++ design techniques, and conceptual object-oriented design patterns.
The book concludes with a useful chapter-by-chapter guide to succeeding in a C++ technical interview.
You will also a find a practical reference guide to the C++ Standard Library on the supplemental Web
site for this book at
www.wrox.com.
What You Need to Use This Book
All you need to use this book is any computer with a C++ compiler. While compilers often differ in their
interpretations of the language, this book focuses on the parts of C++ that have been standardized. The
programs in this book have been tested on Windows, Solaris, and Linux platforms.
Conventions
To help you get the most from the text and keep track of what’s happening, we’ve used a number of con-
ventions throughout the book.
Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles in the text:
❑ We highlight important words when we introduce them
❑ We show keyboard strokes like this: Ctrl+A
❑ We show filenames, URLs, and code within the text like so:
monkey.cpp.
❑ We present code in two different ways:
In code examples we highlight new and important code with a gray background.
The gray highlighting is not used for code that’s less important in the present
context or that has been shown before.
Boxes like this one hold important, not-to-be forgotten information that is directly
relevant to the surrounding text.
03_574841 flast.qxd 12/15/04 3:39 PM Page xxiii
xxiv

Introduction
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually
or to use the source code files that accompany the book. All of the source code used in this book is avail-
able for download at
www.wrox.com. Once at the site, simply locate the book’s title (either by using the
Search box or by using one of the title lists), and click the Download Code link on the book’s detail page
to obtain all the source code for the book.
Because many books have similar titles, you may find it easiest to search by ISBN; for this book the
ISBN is 0-7645-7484-1.
Once you download the code, just decompress it with your favorite compression tool. Alternately, you
can go to the main Wrox code download page at
www.wrox.com/dynamic/books/download.aspx to
see the code available for this book and all other Wrox books.
Errata
We make every effort to ensure that there are no errors in the text or in the code. However, no one is per-
fect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or faulty
piece of code, we would be very grateful for your feedback. By sending in errata you may save another
reader hours of frustration, and at the same time you will be helping us provide even higher-quality
information.
To find the errata page for this book, go to
www.wrox.com and locate the title using the Search box or
one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view
all errata that has been submitted for this book and posted by Wrox editors. A complete book list includ-
ing links to each’s book’s errata is also available at
www.wrox.com/misc-pages/booklist.shtml.
If you don’t spot “your” error on the Book Errata page, go to
www.wrox.com/contact/techsupport
.shtml
and complete the form there to send us the error you have found. We’ll check the information

and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions
of the book.
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based sys-
tem for you to post messages relating to Wrox books and related technologies and interact with other
readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of
your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts,
and your fellow readers are present on these forums.
At
you will find a number of different forums that will help you not only as
you read this book, but also as you develop your own applications. To join the forums, just follow these
steps:
03_574841 flast.qxd 12/15/04 3:39 PM Page xxiv

×