01_574841 ffirs.qxd 12/15/04 3:38 PM Page i Professional C++ Nicholas A. Solter Scott J. Kleper 01_574841 ffirs.qxd 12/15/04 3:38 PM Page i 01_574841 ffirs.qxd 12/15/04 3:38 PM Page i Professional C++ Nicholas A. Solter Scott J. Kleper 01_574841 ffirs.qxd 12/15/04 3:38 PM Page ii 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, MA01923, (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: [email protected]. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACYOR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLYDISCLAIM ALLWARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR APARTICULAR PURPOSE. NO WARRANTYMAYBE CRE- ATED OR EXTENDED BYSALES OR PROMOTIONALMATERIALS. 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 PROFESSIONALSERVICES. IF PROFESSIONALASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOT THE AUTHOR SHALLBE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEB SITE IS REFERRED TO IN THIS WORK AS ACITATION AND/OR APOTENTIALSOURCE OF FUR- THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR- MATION THE ORGANIZATION OR WEB SITE MAYPROVIDE OR RECOMMENDATIONS IT MAYMAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAYHAVE 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 iii 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 iv Author Bios Nicholas A. Solterstudied 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 PGATour 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. Kleperbegan 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. Credits Vice President and Executive Group Publisher Senior Development Editor Richard Swadley Adaobi Obi Tulton Vice President and Publisher Production Editor Joseph B. Wikert Felicia Robinson Executive Editor Media Development Specialist Robert Elliott Richard Graves Editorial Manager Technical Editor Kathryn Malm Bourgoine Jerry Cain Senior Production Editor Text Design & Composition Geraldine Fahey Wiley Composition Services Cover Photographer Adam Tow 02_574841 ftoc.qxd 12/15/04 3:39 PM Page v 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 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 vi 02_574841 ftoc.qxd 12/15/04 3:39 PM Page 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 vii 02_574841 ftoc.qxd 12/15/04 3:39 PM Page 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 viii