Wiley C Plus Plus Timesaving Techniques For Dummies Mar 2005 ISBN 076457986X pdf
C++
Timesaving
™Techniques
FOR
‰
DUMmIES
by Matthew Telles
C++
Timesaving
™Techniques
FOR
‰
DUMmIES
C++
Timesaving
™Techniques
FOR
‰
DUMmIES
by Matthew Telles
™ ® C++ Timesaving Techniques For Dummies Published by Wiley Publishing, Inc.
111 River Street Hoboken, NJ 07030-5774 www.wiley.com Copyright © 2005 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 underSections 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 per-
mission 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: brandreview@wiley.com.
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, Timesaving Techniques, andrelated trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates 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 REPRESENTA-
TIONS 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 FIT-
NESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMO-
TIONAL 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 REN-
DERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS
REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUB-
LISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANI-
ZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF
FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMA-
TION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READ-
ERS 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 800-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: 2005920299ISBN: 0-7645-7986-X Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1
1MA/RU/QS/QV/IN About the Author Matthew Telles is a 20-year veteran of the software-development wars. In his time, he
has seen FORTRAN, COBOL, and other dinosaur languages come and go. Currently a sen- ior software engineer for Research Systems, Inc., his days are spent finding and fixing bugs that other people have created. Besides trying to be tactful, he also enjoys working with other developers to teach the techniques he has mastered over his career. With expertise in programming, designing, documenting, and debugging applications, he has reached the pinnacle of a programmer’s existence: the ability to write his own bio blurbs for books. The author of seven other programming books, Matt lives in Lakewood, Colorado, and pines away for his beloved DEC 10.
Dedication This book is dedicated to my friends and family, without whom I couldn’t have done it.
Author’s Acknowledgments
I would like to acknowledge my employer, Research Systems, for allowing me the time and space to work on this book. In addition, I would like to thank the following people: Carol, for being there and listening; my children, for bringing a ray of sunshine into a gloomy day; and, of course, all of the people behind the scenes as well: the editors, the marketing folk, and that nice guy who kept harassing me for stuff. (Thanks, Chris!)
Publisher’s Acknowledgments We’re proud of this book; please send us your comments through our online regis- tration form located at .
www.dummies.com/register/
Some of the people who helped bring this book to market include the following: Acquisitions, Editorial, and Media Development Composition Services Project Editor: Christopher Morris Project Coordinator: Maridee Ennis Acquisitions Editor: Katie Feltman Layout and Graphics: Melissa Auciello-
Brogan,Denny Hager, Stephanie D. Jumper,
Sr. Copy Editor: Barry Childs-Helton
Melanee Prendergast, Jacque Roth, Heather Ryan,
Technical Editor: John Purdum
Janet Seib
Editorial Manager: Kevin Kirschner Proofreaders: Laura Albert, Laura L. Bowman,
John Greenough, Leeann Harney, Arielle Mannelle,
Media Development Manager: Laura VanWinkle
Joe Niesen, Carl Pierce, Dwight Ramsey, Brian Walls
Media Development Supervisor: Richard Graves Indexer: Ty Koontz Editorial Assistant: Amanda Foxworth Cartoons: Rich Tennant ( www.the5thwave.com ) 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 Joyce Pepple, Acquisitions Director Composition Services Gerry Fahey, Vice President of Production Services Debbie Stailey, Director of Composition Services
Contents at a Glance Introduction
63 Technique 13: Using Enumerations
Part V: Arrays and Templates 173 Technique 30: Creating a Simple Template Class 175 Technique 31: Extending a Template Class 179 Technique 32: Creating Templates from Functions and Methods 186 Technique 33: Working with Arrays 192
Technique 26: Doing Data Validation with Classes 142 Technique 27: Building a Date Class 149 Technique 28: Overriding Functionality with Virtual Methods 162 Technique 29: Using Mix-In Classes 168
Part IV: Classes 107 Technique 21: Creating a Complete Class 109 Technique 22: Using Virtual Inheritance 116 Technique 23: Creating Overloaded Operators 120 Technique 24: Defining Your Own new and delete Handlers 128 Technique 25: Implementing Properties 136
96 Technique 20: Defining Default Arguments for Your Functions and Methods 101
90 Technique 19: Using Pointers to Member Functions
85 Technique 18: Fixing Breaks with Casts
82 Technique 17: Using Namespaces
77 Technique 16: Scoping Your Variables
73 Technique 15: Understanding Constants
70 Technique 14: Creating and Using Structures
59 Technique 12: Creating Your Own Types
1 Part I: Streamlining the Means and Mechanics of OOP
57 Technique 11: Creating Your Own Basic Types
52 Part III: Types
48 Technique 10: Understanding sizeof
45 Technique 9: Macros and Why Not to Use Them
42 Technique 8: Using const Instead of #define
39 Technique 7: Mastering the Evils of Asserts
30 Part II: Working with the Pre-Processor 37 Technique 6: Handling Multiple Operating Systems
19 Technique 4: Inheriting Data and Functionality 23 Technique 5: Separating Rules and Data from Code
12 Technique 3: Customizing a Class with Virtual Functions
7 Technique 2: Using Abstraction to Extend Functionality
5 Technique 1: Protecting Your Data with Encapsulation
Technique 34: Implementing Your Own Array Class 196 Technique 35: Working with Vector Algorithms 200
Part VIII: Utilities 335 Technique 56: Encoding and Decoding Data for the Web 337 Technique 57: Encrypting and Decrypting Strings 343 Technique 58: Converting the Case of a String 349 Technique 59: Implementing a Serialization Interface 354 Technique 60: Creating a Generic Buffer Class 360 Technique 61: Opening a File Using Multiple Paths 366 Part IX: Debugging C++ Applications 373 Technique 62: Building Tracing into Your Applications 375 Technique 63: Creating Debugging Macros and Classes 387 Technique 64: Debugging Overloaded Methods 399
Part X: The Scary (or Fun!) Stuff 405 Technique 65: Optimizing Your Code 407 Technique 66: Documenting the Data Flow 416 Technique 67: Creating a Simple Locking Mechanism 420 Technique 68: Creating and Using Guardian Classes 425 Technique 69: Working with Complex Numbers 432 Technique 70: Converting Numbers to Words 439 Technique 71: Reducing the Complexity of Code 447 Index 455 Technique 36: Deleting an Array of Elements 204 Technique 37: Creating Arrays of Objects 209 Technique 38: Working with Arrays of Object Pointers 213 Technique 39: Implementing a Spreadsheet 216
Part VI: Input and Output 223 Technique 40: Using the Standard Streams to Format Data 225 Technique 41: Reading In and Processing Files 228 Technique 42: How to Read Delimited Files 234
Technique 43: Writing Your Objects as XML 240 Technique 44: Removing White Space from Input 246 Technique 45: Creating a Configuration File 250
Part VII: Using the Built-In Functionality 263 Technique 46: Creating an Internationalization Class 265 Technique 47: Hashing Out Translations 279 Technique 48: Implementing Virtual Files 283 Technique 49: Using Iterators for Your Collections 291 Technique 50: Overriding the Allocator for a Collection Class 297 Technique 51: Using the auto_ptr Class to Avoid Memory Leaks 303 Technique 52: Avoiding Memory Overwrites 307
Technique 53:Throwing, Catching, and Re-throwing Exceptions 312 Technique 54: Enforcing Return Codes 323 Technique 55: Using Wildcards 330
Table of Contents Introduction
47 Technique 9: Macros and
Data from Code
30 The cDate Class
31 Testing the cDate Class
35 Part II: Working with the Pre-Processor 37
Technique 6: Handling Multiple Operating Systems
39 Creating the Header File
39 Testing the Header File
40 Technique 7: Mastering the Evils of Asserts
42 The Assert Problem
42 Fixing the Assert Problem
44 Technique 8: Using const Instead of #define
45 Using the const Construct
46 Identifying the Errors
47 Fixing the Errors
Why Not to Use Them
24 Testing the ConfigurationFile Class
55 Part III: Types
64 Matrix Operations
63 Creating the Matrix Class
62 Technique 12: Creating Your Own Types
60 Testing the Range Class
59 Implementing the Range Class
57 Technique 11: Creating Your Own Basic Types
54 Using sizeof with Pointers
48 Initiating a Function with a
52 Evaluating the Results
52 Using the sizeof Function
51 Technique 10: Understanding sizeof
50 Using Macros Appropriately
49 Fixing What Went Wrong with the Macro
String Macro — Almost
27 Technique 5: Separating Rules and
23 Implementing a ConfigurationFile Class
1 Saving Time with This Book
4 Icons Used in This Book
2 What’s Available on the Companion Web Site?
2 Conventions Used in This Book
2 What’s In This Book
3 Part I: Streamlining the Means and
Mechanics of OOP
3 Part II: Working with the Pre-Processor
3 Part III: Types
3 Part IV: Classes
3 Part V: Arrays and Templates
3 Part VI: Input and Output
4 Part VII: Using the Built-in Functionality
4 Part VIII: Utilities
4 Part IX: Debugging C++ Applications
4 Part X: The Scary (or Fun!) Stuff
4 Part I: Streamlining the Means and
Functionality
12 Testing the Mailing-List Application
22 Technique 4: Inheriting Data and
21 Why Do the Destructors Work?
20 Testing the Virtual Function Code
19 Customizing a Class with Polymorphism
with Virtual Functions
17 Technique 3: Customizing a Class
12 Creating a Mailing-List Application
Mechanics of OOP
to Extend Functionality
10 Technique 2: Using Abstraction
7 Making Updates to an Encapsulated Class
an Encapsulated Class
7 Creating and Implementing
5 Technique 1: Protecting Your Data with Encapsulation
65 C++ Timesaving Techniques For Dummies
Part IV: Classes 107 Technique 21: Creating a Complete Class 109 Creating a Complete Class Template 110 Testing the Complete Class 113 Technique 22: Using Virtual Inheritance 116 Implementing Virtual Inheritance 118 Correcting the Code 119 Technique 23: Creating Overloaded Operators 120 Rules for Creating Overloaded Operators 121 Using Conversion Operators 122 Using Overloaded Operators 122 Testing the MyString Class 125 Technique 24: Defining Your Own new and delete Handlers 128
88 Technique 18: Fixing Breaks with Casts
80 Using the const Keyword
81 Technique 16: Scoping Your Variables
82 Illustrating Scope
83 Interpreting the Output
84 Technique 17: Using Namespaces
85 Creating a Namespace Application
86 Testing the Namespace Application
90 Using Casts
Rules for Implementing new and delete Handlers 129 Overloading new and delete Handlers 129 Testing the Memory Allocation Tracker 133
91 Addressing the Compiler Problems
93 Testing the Changes
to Member Functions
97 Updating Your Code with Member-Function Pointers
99 Testing the Member Pointer Code
for Your Functions and Methods 101
Customizing the Functions We Didn’t Write 102 Customizing Functions We Wrote Ourselves 103 Testing the Default Code 105 Fixing the Problem 106
78 Testing the Constant Application
77 Implementing Constant Variables
77 Defining Constants
Implementing Properties 137 Testing the Property Class 140
Implementing Data Validation with Classes 142 Testing Your SSN Validator Class 146
Technique 27: Building a Date Class 149
Creating the Date Class 150 Implementing the Date Functionality 152 Testing the Date Class 159 Some Final Thoughts on the Date Class 161
Technique 25: Implementing Properties 136
75 Technique 15: Understanding Constants
66 Multiplying a Matrix by Scalar Values, Take 2
67 Testing the Matrix Class
68 Technique 13: Using Enumerations
70 Implementing the Enumeration Class
71 Testing the Enumeration Class
72 Technique 14: Creating and Using Structures 73 Implementing Structures
74 Interpreting the Output
Technique 26: Doing Data Validation with Classes 142
94 Technique 19: Using Pointers
96 Implementing Member-Function Pointers
99 Technique 20: Defining Default Arguments
Technique 28: Overriding Functionality with Virtual Methods 162
Technique 29: Using Mix-In Classes 168
Implementing Mix-In Classes 169 Multiplying a Matrix by a Scalar Value
Creating a Factory Class 163 Testing the Factory 166 Enhancing the Manager Class 167
Table of Contents
Examining Allocations of Arrays and Pointers 204
Part VII: Using the Built-In Functionality 263 Technique 46: Creating an Internationalization Class 265 Building the Language Files 266 Creating an Input Text File 272 Reading the International File 272 Testing the String Reader 277 Technique 47: Hashing Out Translations 279 Creating a Translator Class 279 Testing the Translator Class 281 Technique 48: Implementing Virtual Files 283 Creating a Virtual File Class 283 Testing the Virtual File Class 289 Improving Your Virtual File Class 290 Technique 49: Using Iterators for Your Collections 291 Technique 50: Overriding the Allocator for a Collection Class 297
Creating the Configuration-File Class 251 Setting Up Your Test File 260 Testing the Configuration-File Class 260
Part VI: Input and Output 223 Technique 40: Using the Standard Streams to Format Data 225 Working with Streams 225 Technique 41: Reading In and Processing Files 228 Testing the File-Reading Code 232 Creating the Test File 233 Technique 42: How to Read Delimited Files 234 Reading Delimited Files 234 Testing the Code 238 Technique 43: Writing Your Objects as XML 240 Creating the XML Writer 241 Testing the XML Writer 243 Technique 44: Removing White Space from Input 246 Technique 45: Creating a Configuration File 250
Creating the Column Class 217 Creating the Row Class 218 Creating the Spreadsheet Class 219 Testing Your Spreadsheet 221
Technique 39: Implementing a Spreadsheet 216
Creating an Array of Heterogeneous Objects 213
Technique 37: Creating Arrays of Objects 209 Technique 38: Working with Arrays of Object Pointers 213
Technique 36: Deleting an Array of Elements 204
Part V: Arrays and Templates 173 Technique 30: Creating a Simple Template Class 175 Technique 31: Extending a Template Class 179 Implementing Template Classes in Code 180 Testing the Template Classes 182 Using Non-class Template Arguments 184 Technique 32: Creating Templates from Functions and Methods 186
Working with Vector Algorithms 200
Technique 35: Working with Vector Algorithms 200
Creating the String Array Class 196
Technique 34: Implementing Your Own Array Class 196
Using the Vector Class 192
Technique 33: Working with Arrays 192
Implementing Function Templates 186 Creating Method Templates 189
Creating a Custom Memory Allocator 298 C++ Timesaving Techniques For Dummies Technique 51: Using the auto_ptr Class to Avoid Memory Leaks 303
Using the auto_ptr Class 303
Creating the Buffer Class 361 Testing the Buffer Class 364
Part X: The Scary (or Fun!) Stuff 405 Technique 65: Optimizing Your Code 407 Making Functions Inline 407 Avoiding Temporary Objects 408 Passing Objects by Reference 410 Postponing Variable Declarations 412 Choosing Initialization Instead of Assignment 413 Technique 66: Documenting the Data Flow 416 Learning How Code Operates 416 Testing the Properties Class
Adding Logging to the Application 401
Technique 64: Debugging Overloaded Methods 399
The assert Macro 387 Logging 389 Testing the Logger Class 390 Design by Contract 392
Technique 63: Creating Debugging Macros and Classes 387
Implementing the Flow Trace Class 376 Testing the Flow Trace System 379 Adding in Tracing After the Fact 380
Part IX: Debugging C++ Applications 373 Technique 62: Building Tracing into Your Applications 375
Creating the Multiple-Search-Path Class 367 Testing the Multiple-Search-Path Class 369
Technique 61: Opening a File Using Multiple Paths 366
Technique 60: Creating a Generic Buffer Class 360
Technique 52: Avoiding Memory Overwrites 307
Implementing the Serialization Interface 355 Testing the Serialization Interface 358
Technique 59: Implementing a Serialization Interface 354
to Convert Strings 350 Testing the String Conversions 351
Part VIII: Utilities 335 Technique 56: Encoding and Decoding Data for the Web 337 Creating the URL Codec Class 338 Testing the URL Codec Class 340 Technique 57: Encrypting and Decrypting Strings 343 Implementing the Rot13 Algorithm 344 Testing the Rot13 Algorithm 345 Implementing the XOR Algorithm 346 Testing the XOR Algorithm 347 Technique 58: Converting the Case of a String 349 Implementing the transform Function
Creating the Wildcard Matching Class 331 Testing the Wildcard Matching Class 333
Technique 54: Enforcing Return Codes 323 Technique 55: Using Wildcards 330
Throwing and Logging Exceptions 312 Dealing with Unhandled Exceptions 317 Re-throwing Exceptions 319
Technique 53: Throwing, Catching, and Re-throwing Exceptions 312
Creating a Memory Safe Buffer Class 307
418 Table of Contents Technique 67: Creating a Simple Locking Mechanism 420
Creating the Locking Mechanism 421 Testing the Locking Mechanism 422
Technique 68: Creating and Using Guardian Classes 425
Creating the File-Guardian Class 426 Testing the File-Guardian Class 430
Technique 69: Working with Complex Numbers 432
Implementing the Complex Class 433 Testing the Complex Number Class 436
Technique 70: Converting Numbers to Words 439
Creating the Conversion Code 440 Testing the Conversion Code 446
Technique 71: Reducing the Complexity of Code 447
A Sample Program 447 Componentizing 449 Restructuring 451 Specialization 452
Index 455
Introduction
- is a flexible, powerful programming language with hundreds of thousands of applications. However, the knowledge of how to take advantage of its full potential comes only with time and experience.
C
That’s where this book comes in. Think of it as a “cookbook” for solving your programming problems, much as The Joy of Cooking is a guide to solving your dinner dilemmas.
C++ Timesaving Techniques For Dummies is a book for the beginning-to-
advanced C++ programmer who needs immediate answers to the prob- lems that crop up in the professional software-development world. I assume that you have prior programming experience, as well as experi- ence specifically with the C++ programming language. “Fluff” — like dis- cussions of looping structures or defining variables, or the basics of compiling applications — is kept to a minimum here. Instead, I offer quick, step-by-step instructions for solving specific problems in C++. Each technique includes example code — which you are welcome to use in your own applications, or modify as you see fit. This is literally a case of “steal this code, please.” C++ is a language that lends itself well to component-based design and implementation. This means that you can take a piece from here and a piece from there to implement the solution that you have in mind.
C++ Timesaving Techniques For Dummies is not an operating-system-
specific (or even compiler-specific) book. The techniques and code that you find here should work on all compilers that support the standard C++ language, and on all operating systems for which a standard com- piler exists. This book is intended to be as useful to the Unix programmer as to the Microsoft Windows programmer, and just as useful for program- ming with X-windows as it is for .Net.
My goal in writing this book is to empower you with some of the stronger features of C++, as well as some great tips and methods to solve everyday problems, without the headaches and lost time that go with trying to fig- ure out how to use those tools. C++ provides simple, fast, powerful solu- tions to meet the demands of day-to-day programming — my goal is to save you time while making the tools clear and easy to use. Introduction Saving Time with This Book What’s Available on the Companion Web Site?
The Timesaving Techniques For Dummies books focus on big-payoff techniques that save you time, either The companion Web site for this book contains all on the spot or somewhere down the road. And these the source code shown for the techniques and exam- books get to the point in a hurry, with step-by-step ples listed in this book. This resource can save you instructions to pace you through the tasks you need considerable typing when you want to use the code to do, without any of the fluff you don’t want. I’ve iden- in your own applications, as well as allowing you to tified more than 70 techniques that C++ programmers easily refer back to the original code if you modify need to know to make the most of their time. In addi- the things you find here. You can find the site at tion, each technique includes code samples that make
. www.dummies.com/go/cpluspluststfd programming a breeze. Decide for yourself how to use this book: Read it cover to cover if you like, or skip
Obviously, in order to utilize the code in the book, right to the technique that interests you the most. you will need a C++ compiler. The code in this book was all tested with the GNU C++ compiler, a copy of
In C++ Timesaving Techniques For Dummies, you can which you will find on the GNU organization’s Web find out how to site: . This compiler is a public-domain www.gnu.org
(read: free) compiler that you can use in your own ⻬ Reduce time-consuming tasks: I’m letting you in development, or simply to test things on computers on more than 70 tips and tricks for your C++ sys- that don’t have a full-blown commercial develop- tem, so you can spend more time creating great ment system. The GNU C++ compiler contains all the results and less time fiddling with a feature so standard header files, libraries, debuggers, and that it works correctly. other tools that C++ programmers expect.
⻬ Take your skills up a notch: You’re already famil- iar with the basics of using C++. Now this book If you already own another compiler, such as Visual takes you to the next level, helping you become a Studio, Borland’s C++Builder, or another compiler, more powerful programmer. hey, no worries. The code you find here should work with any of these compilers, as long as you follow
⻬ Work with the basics of C++ to meet your needs: I the standards for defining header files and including show you how to bend the fundamentals of object- code libraries. oriented programming and the pre-processor so that your programs work faster and more reliably.
⻬ Improve your skills with types, classes, arrays,
Conventions Used in This Book and templates: Fine-tuning your abilities with
these elements will improve your programs’ When I describe output from the compiler, operating functionality and make your code more readable. system, or application you’re developing, you will
⻬ Understand the finer points of input and output: see it in a distinctive typeface that looks like this: Improving the way you work with input and out- put will reduce memory loss and increase speed.
This is some output ⻬ Use built-in functionality and utilities: Gaining
Source-code listings — such as the application familiarity with these features will help you get you’re developing and feeding to the compiler to the most out of what C++ already offers. mangle into executable code — will look like this:
⻬ Improve your debugging skills: Getting better at debugging will speed up the whole programming process.
What’s In This Book L
ISTING
// This is a loop for ( int i=0; i<10; ++i ) printf(“This is line %d\n”, i );
If you are entering code by hand, you should enter it as you see it in the book, although spaces and blank lines won’t matter. Comments can be skipped, if you so choose, but in general, the code is commented as it would be in a production environment. In general, the code and text in the book should be quite straightforward. The entries are all in list format, taking you step by step through the process of creating source files, compiling them, and running the resulting application. The code is all compiler-agnostic — that is, it doesn’t indicate (because it doesn’t know) the specific compiler commands you will use for the compiler you have on your machine. Please refer to your compiler’s docu- mentation if you have specific questions about the compilation and linking process for your specific compiler or operating system.
What’s In This Book
This book is organized into parts — groups of tech- niques about a common subject that can save you time and help you get your program written fast and running better. Each technique is written to be inde- pendent of the others; you need only implement the techniques that benefit you and your users.
Part I: Streamlining the Means and Mechanics of OOP In this part, you learn the basic concepts of object-
oriented programming and how they apply to the C++ programming language.
Part II: Working with the Pre-Processor The C++ pre-processor is a powerful tool for cus-
tomizing your application, making your code more readable, and creating portable applications. In this section, you get some handy ways to wring the most out of the pre-processor; some handy techniques explain how to create portable code, and the voice of experience reveals why you should avoid the assert macro.
Part III: Types The C++ language is rich in data types and user-
definable types. In this section, we explore using the built-in types of the language, as well as creating your own types that can be used just like the built-in ones. You find techniques in this section that explain structures and how you can use them. You also zero in on enumerations and creating default arguments for methods.
Part IV: Classes The core of the C++ programming language is the class. In this section, you get a look at how to create
complete classes that work in any environment — as well as how to perform data validation and manipu- lation, create properties for your class, and inherit from other people’s classes.
Part V: Arrays and Templates Container classes are a core element of the Standard Template Library (STL), an important part of the C++
programming environment. In this section, you get the goods on working with the various container classes, as well as creating your own containers. Here’s where to find out how to iterate over a collec- tion of objects, and how to allocate and de-allocate blocks of objects. Introduction
When these things happen, it is extremely important
Part VI: Input and Output
that you understand how to track down the issues in It would be a rare program indeed that did not have the code. In this section, you learn valuable tech- some form of input and output. After all, why would niques for creating tracing macros, tracking down a user bother to run a program that could not be memory leaks, and checking for errors at run-time. controlled in some way, or at least yield some sort of useful information? In this section, we learn all about
Part X: The Scary (or Fun!) Stuff
various forms of input and output, from delimited file input to XML file output, and everything in This part contains techniques to help you take con- between. trol of the complexity of your code, and ways you can avoid being intimidated by convoluted code you might run into while working. Not being afraid of
Part VII: Using the Built-in Functionality
your code is the number-one area of importance in One hallmark of the C++ programming language is programming; this section will aid you in that its extensibility and reusability. Why reinvent the endeavor. wheel every time you write an application? C++ makes it easy to avoid this pitfall by providing a ton of built-in functionality. In this section, you get to
Icons Used in This Book
use that built-in functionality — in particular, the C++ library and STL — to implement a complete
Each technique in this book has icons pointing to internationalization class. You also get pointers on special information, sometimes quite emphatically. avoiding memory leaks, using hash tables, and over- Each icon has its own purpose. riding allocators for a container class.
When there’s a way to save time, either now or in the future, this icon leads the way. Home
Part VIII: Utilities in on these icons when every second counts. The single best way to learn C++ techniques is to
look at the way that other people implement various This icon points to handy hints that help you things. This section contains simple utilities that can work through the steps in each technique, or sharpen your coding techniques, and it provides offer handy troubleshooting info. valuable code that you can drop directly into your applications. You will find techniques here for
These icons are your trail of breadcrumbs, encoding and decoding data, converting data into a leading back to information that you’ll want to format that the World Wide Web can understand, keep in mind. and opening a file using multiple search paths.
When you see a Warning icon, there’s a
Part IX: Debugging C++ Applications chance that your data or your system is at risk. You won’t see many of these, but when you One of the most important things to understand do, proceed with caution.
about programs is that they break. Things go wrong, code behaves in unexpected ways, and users do things you (and sometimes they) didn’t intend.
Part I
Streamliningthe Means and
Mechanics of OOP
Protecting Your Data with Encapsulation
Technique
1
he dictionary defines encapsulation as “to encase in or as if in a capsule” and that is exactly the approach that C++ uses. An object
Save Time By
is a “capsule” and the information and processing algorithms that ⻬ Understanding
T
it implements are hidden from the user. All that the users see is the encapsulation functional-level interface that allows them to use the class to do the job
⻬ Creating and implement- they need done. By placing the data within the interface, rather than ing an encapsulated allowing the user direct access to it, the data is protected from invalid class values, wrongful changes, or improper coercion to new data types.
⻬ Making updates to an encapsulated class Most time wasted in application development is spent changing code that has been updated by another source. It doesn’t really add any- thing to your program, but it does take time to change things when someone has modified the algorithm being used. If you hide the algo- rithm from the developer — and provide a consistent interface — you will find that it takes considerably less time to change the application when the base code changes. Since the user only cares about the data and how it is computed, keeping your algorithm private and your interface constant protects the data integrity for the user.
Creating and Implementing an Encapsulated Class
Listing 1-1 presents the class, an encapsulated method of StringCoding encryption. The benefit of encapsulation is, in effect, that it cuts to the chase: The programmer utilizing our class knows nothing
StringCoding about the algorithm used to encrypt strings — and doesn’t really need to know what data was used to encrypt the string in the first place. Okay, but why do it? Well, you have three good reasons to “hide” the implemen- tation of an algorithm from its user:
⻬ Hiding the implementation stops people from fiddling with the input data to make the algorithm work differently. Such changes may be meant to make the algorithm work correctly, but can easily mess it up; either way, the meddling masks possible bugs from the developers. Technique 1: Protecting Your Data with Encapsulation
⻬ Hiding the algorithm makes it easy to replace the 1.
In the code editor of your choice, create a new
implementation with a more workable alternative
file to hold the code for the definition of your if one is found. source file.
⻬ Hiding the algorithm makes it more difficult for In this example, the file is named , ch01.cpp people to “crack” your code and decrypt your although you can use whatever you choose. data.
2. Type the code from Listing 1-1 into your file, substituting your own names for the italicized
The following list of steps shows you how to create constants, variables, and filenames. and implement this encapsulated method:
Or better yet, copy the code from the source file included on this book’s companion Web site.
L
ISTING 1-1: T HE S TRING C ODING C LASS
#include <stdio.h> #include <string> class StringCoding { private:
// The key to use in encrypting the string std::string sKey; public:
// The constructor, uses a preset key
StringCoding ( void )
{ sKey = “ATest”; } // Main constructor, allows the user to specify a key
StringCoding ( const char *strKey )
{ if ( strKey )
sKey = strKey;
else
sKey = “ATest”;
} // Copy constructor
StringCoding ( const StringCoding& aCopy )
{
sKey = aCopy.sKey;
} public: // Methods std::string Encode( const char *strIn ); std::string Decode( const char *strIn ); private: std::string Xor( const char *strIn );
};
Creating and Implementing an Encapsulated Class
std::string StringCoding::Xor( const char *strIn ) { std::string sOut = “”; int nIndex = 0; for ( int i=0; i<(int)strlen(strIn); ++i ) { char c = (strIn[i] ^ sKey[nIndex]); sOut += c; nIndex ++; if ( nIndex == sKey.length() ) nIndex = 0;
} return sOut; } // For XOR encoding, the encode and decode methods are the same. std::string StringCoding::Encode( const char *strIn ) { return Xor( strIn ); } std::string StringCoding::Decode( const char *strIn ) { return Xor( strIn ); } int main(int argc, char **argv) { if ( argc < 2 )
{ printf(“Usage: ch1_1 inputstring1 [inputstring2...]\n”); exit(1);
}
StringCoding
key(“XXX”); for ( int i=1; i<argc; ++i ) { std::string sEncode = key.Encode( argv[i] ); printf(“Input String : [%s]\n”, argv[i] ); printf(“Encoded String: [%s]\n”, sEncode.c_str() ); std::string sDecode = key.Decode( sEncode.c_str() ); printf(“Decoded String: [%s]\n”, sDecode.c_str() );
} printf(“%d strings encoded\n”, argc-1); return 0;
}
Technique 1: Protecting Your Data with Encapsulation 3.
Save the source code as a file in the code-editor Making Updates to an application and then close the code editor.
Encapsulated Class 4.
Compile your completed source code, using your favorite compiler on your favorite operat-
One of the benefits of encapsulation is that it makes ing system. updating your hidden data simple and convenient.
5. Run your new application on your favorite
With encapsulation, you can easily replace the operating system. underlying encryption algorithm in Listing 1-1 with an alternative if one is found to work better. In our
If you have done everything properly, you should original algorithm, we did an “exclusive logical or” see the output shown here in the console window of to convert a character to another character. In the your operating system: following example, suppose that we want to use a different method for encrypting strings. For simplic-
$ ./ch1_1.exe “hello” ity, suppose that this new algorithm encrypts strings
Input String : [hello] Encoded String: [0=447] simply by changing each character in the input Decoded String: [hello] string to the next letter position in the alphabet: An
1 strings encoded
a becomes a b, a c becomes a d, and so on. Obviously,
our decryption algorithm would have to do the exact Note that our input and decoded strings are the opposite, subtracting one letter position from the same — and that the encoded string is completely input string to return a valid output string. We could indecipherable (as a good encrypted string should then modify the method in Listing 1-1 to reflect
Encode be). And any programmer using the object will never this change. The following steps show how: see the algorithm in question! 1.
Reopen the source file in your code editor.
In this example, we called the source file . ch01.cpp 2.
Modify the code as shown in Listing 1-2. L
ISTING 1-2: U PDATING THE S TRING C ODING C LASS
std::string StringCoding::Encode( const char *strIn ) { std::string sOut = “”; for ( int i=0; i<(int)strlen(strIn); ++i ) { char c = strIn[i]; c ++; sOut += c;
} return sOut; } std::string StringCoding::Decode( const char *strIn ) { std::string sOut = “”;
Making Updates to an Encapsulated Class
3. Save the source code as a file in the code editor and then close the code editor.
4. Compile the application, using your favorite compiler on your favorite operating system.
5. Run the application on your favorite operating system.
You might think that this approach would have an impact on the developers who were using our class. In fact, we can make these changes in our class (check out the resulting program on this book’s companion Web site as ch1_1a.cpp