Thinking in C++ 2nd edition VERSION TICA15 Revision history: ToDo: Fix autobuild of make test makefile (remove backslashes); add test arguments (what about some kind of autofill via redirection?). Differentiate copy-assignment operator= from other forms of operator=. HorseRace game as example of random number generator in early chapter? Change header numbering scheme as suggested? Request for description/example of recursion. TICA15: April 22, 1999. Rewrote chapter 4 and added exercises. TICA14, March 28, 1999. Rewrote Chapter 2 and 3. I think they’re both finished. Chapter 3 is rather big since it covers C syntax fundamentals, along with some C++ basics. Added many exercises to Chapters 2 & 3, to complete them both. Chapter 3 was a “hump” chapter; I think the others in section one shouldn’t be as hard. Tried to conform all code in the book to the convention of “type names start with uppercase letters, functions and variables start with lowercase letters”. TICA13, March 9, 1999. Thorough rewrite of chapter one, including the addition of UML diagrams. I think chapter one is finished, now. Reorganized material elsewhere in the book, but that is still in transit. My goal right now is to move through all the chapters in section one, in order. TICA12, January 15, 1999. Lots of work done on the Design Patterns chapter. All the exsting programs are now modified and redesigned (significantly!) to compile under C++. Added several new examples. Much of the prose in this chapter still needs work, and more patterns and examples are forthcoming. Changed ExtractCode.cpp so that it generates “bugs” targets for each makefile, containing all the files that won’t compile with a particular compiler so they can be re-checked with new compilers. Generates a master in the book’s root directory called makefile.bugs which descends into each subdirectory and executes make with “bugs” as a target and the –i flag so you’ll see all the errors. TICA11, January 7, 1999. Completed the STL Algorithms chapter (significant additions and changes), edited and added examples the STL containers chapter. Added many exercises at the ends of both chapters. I consider these both completed now. Added an example or two to the strings chapter. TICA10, December 28, 1998. Complete rewrite of the ExtractCode.cpp program to automatically generate makefiles for each compiler that the book tests, excluding files that the compiler can’t handle (these are in a special list in the appendices, so you can see what breaks a compiler, and you can create your own). You now don’t need to extract the files yourself (although you still can, for special cases) but instead you just download and unzip a file. All the files in the book (with the exception of the files that are still in Java) now compile with at least one Standard C++ compiler. Added the trim.h, SiteMapConvert.cpp and StringCharReplace.cpp examples to the strings chapter. Added the ProgVals example to chapter 20. Removed all the strlwr( ) uses (it’s a non-standard function). TICA9, December 15, 1998. Massive work completed on the STL Algorithms chapter; it’s quite close to being finished. The long delay was because (1) This chapter took a lot of research and thinking, including other research such as templates; you’ll notice the “advanced templates” chapter has more in it’s outline (2) I was traveling and giving seminars, etc. I’m entering a two-month hiatus where I’m primarily working on the book and should get a lot accomplished. TICA8, September 26, 1998. Completed the STL containers chapter. TICA7, August 14, 1998. Strings chapter modified. Other odds and ends. TICA6, August 6, 1998. Strings chapter added, still needs some work but it’s in fairly good shape. The basic structure for the STL Algorithms chapter is in place and “just” needs to be filled out. Reorganized the chapters; this should be very close to the final organization (unless I discover I’ve left something out). TICA5, August 2, 1998: Lots of work done on this version. Everything compiles (except for the design patterns chapter with the Java code) under Borland C++ 5.3. This is the only compiler that even comes close, but I have high hopes for the next verison of egcs. The chapters and organization of the book is starting to take on more form. A lot of work and new material added in the “STL Containers” chapter (in preparation for my STL talks at the Borland and SD conferences), although that is far from finished. Also, replaced many of the situations in the first edition where I used my home-grown containers with STL containers (typically vector). Changed all header includes to new style (except for C programs): <iostream> instead of <iostream.h>, <cstdlib> instead of <stdlib.h>, etc. Adjustment of namespace issues (“using namespace std” in cpp files, full qualification of names in header files). Added appendix A to describe coding style (including namespaces). Added “require.h” error testing code and used it universally. Rearranged header include order to go from more general to more specific (consistency and style issue described in appendix A). Replaced ‘main( ) {}’ form with ‘int main( ) { }’ form (this relies on the default “return 0” behavior, although some compilers, notably VC++, give warnings). Went through and implemented the class naming policy (following the Java/Smalltalk policy of starting with uppercase etc.) but not the member functions/data members (starting with lowercase etc.). Added appendix A on coding style. Tested code with my modified version of Borland C++ 5.3 (cribbed a corrected ostream_iterator from egcs and <sstream> from elsewhere) so not all the programs will compile with your compiler (VC++ in particular has a lot of trouble with namespaces). On the web site, I added the broken-up versions of the files for easier downloads. TICA4, July 22, 1998: More changes and additions to the “CGI Programming” section at the end of Chapter 23. I think that section is finished now, with the exception of corrections. TICA3, July 14, 1998: First revision with content editing (instead of just being a posting to test the formatting and code extraction process). Changes in the end of Chapter 23, on the “CGI Programming” section. Minor tweaks elsewhere. RTF format should be fixed now. TICA2, July 9, 1998: Changed all fonts to Times and Courier (which are universal); changed distribution format to RTF (readable by most PC and Mac Word Processors, and by at least one on Linux: StarOffice from www.caldera.com. Please let me know if you know about other RTF word processors under Linux). __________________________________________________________________________ The instructions on the web site (http://www.BruceEckel.com/ThinkingInCPP2e.html) show you how to extract code for both Win32 systems and Linux (only Red Hat Linux 5.0/5.1 has been tested). The contents of the book, including the contents of the source-code files generated during automatic code extraction, are not intended to indicate any accurate or finished form of the book or source code. Please only add comments/corrections using the form found on http://www.BruceEckel.com/ThinkingInCPP2e.html Please note that the book files are only available in Rich Text Format (RTF) or plain ASCII text without line breaks (that is, each paragraph is on a single line, so if you bring it into a typical text editor that does line wrapping, it will read decently). Please see the Web page for information about word processors that support RTF. The only fonts used are Times and Courier (so there should be no font difficulties); if you find any other fonts please report the location. Thanks for your participation in this project. Bruce Eckel “This book is a tremendous achievement. You owe it to yourself to have a copy on your shelf. The chapter on iostreams is the most comprehensive and understandable treatment of that subject I’ve seen to date.” Al Stevens Contributing Editor, Doctor Dobbs Journal “Eckel’s book is the only one to so clearly explain how to rethink program construction for object orientation. That the book is also an excellent tutorial on the ins and outs of C++ is an added bonus.” Andrew Binstock Editor, Unix Review “Bruce continues to amaze me with his insight into C++, and Thinking in C++ is his best collection of ideas yet. If you want clear answers to difficult questions about C++, buy this outstanding book.” Gary Entsminger Author, The Tao of Objects “Thinking in C++ patiently and methodically explores the issues of when and how to use inlines, references, operator overloading, inheritance and dynamic objects, as well as advanced topics such as the proper use of templates, exceptions and multiple inheritance. The entire effort is woven in a fabric that includes Eckel’s own philosophy of object and program design. A must for every C++ developer’s bookshelf, Thinking in C++ is the one C++ book you must have if you’re doing serious development with C++.” Richard Hale Shaw Contributing Editor, PC Magazine Thinking In C++ Bruce Eckel President, MindView Inc. Prentice Hall PTR Upper Saddle River, New Jersey 07458 http://www.phptr.com Publisher: Alan Apt Production Editor: Mona Pompilli Development Editor: Sondra Chavez Book Design, Cover Design and Cover Photo: Daniel Will-Harris, [email protected] Copy Editor: Shirley Michaels Production Coordinator:Lori Bulwin Editorial Assistant: Shirley McGuire © 1998 by Bruce Eckel, MindView, Inc. Published by Prentice Hall Inc. A Paramount Communications Company Englewood Cliffs, New Jersey 07632 The information in this book is distributed on an “as is” basis, without warranty. While every precaution has been taken in the preparation of this book, neither the author nor the publisher shall have any liability to any person or entitle with respect to any liability, loss or damage caused or alleged to be caused directly or indirectly by instructions contained in this book or by the computer software or hardware products described herein. All rights reserved. No part of this book may be reproduced in any form or by any electronic or mechanical means including information storage and retrieval systems without permission in writing from the publisher or author, except by a reviewer who may quote brief passages in a review. Any of the names used in the examples and text of this book are fictional; any relationship to persons living or dead or to fictional characters in other works is purely coincidental. Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 ISBN 0-13-917709-4 Prentice-Hall International (UK) Limited, London Prentice-Hall of Australia Pty. Limited, Sydney Prentice-Hall Canada, Inc., Toronto Prentice-Hall Hisapnoamericana, S.A., Mexico Prentice-Hall of India Private Limited, New Delhi Prentice-Hall of Japan, Inc., Tokyo Simon & Schuster Asia Pte. Ltd., Singapore Editora Prentice-Hall do Brasil, Ltda., Rio de Janeiro dedication to the scholar, the healer, and the muse What’s inside... Thinking in C++ 2nd edition VERSION A better C.........................................56 TICA15..............................................1 You’re already on the learning curve56 Efficiency.........................................56 Preface 17 Systems are easier to express and understand........................................57 Prerequisites...............................17 Maximal leverage with libraries.......57 Thinking in C...................................17 Source-code reuse with templates.....57 Error handling..................................57 Learning C++.............................18 Programming in the large.................58 Goals..........................................19 Strategies for transition..............58 Chapters.....................................20 Guidelines........................................58 Exercises....................................24 Management obstacles......................60 Source code................................24 Summary....................................61 Coding standards..............................25 2: Making & using objects 63 Language standards....................26 Language support.............................26 Seminars & CD Roms................27 The process of language translation63 Errors..........................................27 Interpreters.......................................64 Compilers.........................................64 Acknowledgements....................27 The compilation process...................65 Tools for separate compilation...66 1: Introduction to objects 29 Declarations vs. definitions..............67 Linking.............................................71 The progress of abstraction........29 Using libraries..................................72 An object has an interface..........31 Your first C++ program..............73 The hidden implementation........33 Using the iostreams class..................73 Reusing the implementation......34 Namespaces......................................74 Fundamentals of program structure..75 Inheritance: reusing the interface35 "Hello, world!".................................76 Is-a vs. is-like-a relationships...........39 Running the compiler.......................77 Interchangeable objects with More about iostreams.................77 polymorphism............................40 Character array concatenation..........78 Creating and destroying objects.43 Reading input...................................78 Exception handling: dealing with Simple file manipulation..................79 errors..........................................44 Introducing strings....................80 Analysis and design....................45 Reading and writing files...........82 Phase 0: Make a plan........................47 Introducing vector.....................84 Phase 1: What are we making?.........48 Summary....................................87 Phase 2: How will we build it?.........50 Exercises....................................88 Phase 3: Build it...............................53 Phase 4: Iteration..............................53 Plans pay off.....................................55 Why C++ succeeds.....................55 3: The C in C++ 91 Turning variables and expressions into strings.............................................151 The C assert( ) macro.....................152 Creating functions......................91 Make: an essential tool for separate Using the C function library.............94 compilation..............................153 Creating your own libraries with the librarian............................................94 Make activities...............................154 Controlling execution.................95 Makefiles in this book....................156 True and false...................................95 An example makefile.....................156 if-else................................................95 Summary..................................158 while................................................96 Exercises..................................159 do-while...........................................97 for....................................................98 4: Data abstraction 162 The break and continue Keywords.99 switch.............................................100 A tiny C-like library.................163 Introduction to operators..........102 Dynamic storage allocation............166 Precedence.....................................102 Bad guesses....................................169 Auto increment and decrement.......102 What's wrong?..........................170 Introduction to data types.........103 The basic object.......................171 Basic built-in types.........................103 What's an object?.....................177 bool, true, & false..........................104 Abstract data typing.................178 Specifiers........................................105 Introduction to Pointers..................107 Object details...........................178 Modifying the outside object..........111 Header file etiquette.................180 Introduction to C++ references.......113 Importance of header files..............180 Pointers and references as modifiers114 The multiple-declaration problem..182 Scoping.....................................116 The preprocessor directives #define, Defining variables on the fly..........117 #ifdef and #endif............................182 Specifying storage allocation...119 A standard for header files..............183 Global variables..............................119 Namespaces in headers...................184 Local variables...............................120 Using headers in projects................184 static..............................................120 Nested structures......................185 extern.............................................122 Global scope resolution..................188 Constants........................................123 Summary..................................189 volatile...........................................124 Exercises..................................189 Operators and their use.............125 Assignment.....................................125 5: Hiding the implementation Mathematical operators..................125 Relational operators........................127 193 Logical operators............................127 Bitwise operators............................128 Setting limits............................193 Shift operators................................128 C++ access control...................194 Unary operators..............................131 protected........................................195 The ternary operator.......................132 Friends.....................................196 The comma operator.......................132 Common pitfalls when using operators133 Nested friends.................................198 Casting operators............................133 Is it pure?........................................200 sizeof – an operator by itself...........134 Object layout............................200 The asm keyword...........................134 The class..................................201 Explicit operators...........................134 Modifying Stash to use access control203 Composite type creation...........135 Modifying Stack to use access control204 Aliasing names with typedef..........135 Handle classes..........................205 Combining variables with struct....136 Visible implementation..................205 Clarifying programs with enum.....139 Reducing recompilation..................206 Saving memory with union............140 Summary..................................208 Arrays.............................................141 Exercises..................................209 Debugging hints.......................149 Debugging flags.............................149 6: Initialization & cleanup 211 Exercises..................................267 9: Inline functions 269 Guaranteed initialization with the constructor................................212 Preprocessor pitfalls.................269 Guaranteed cleanup with the Macros and access..........................272 destructor..................................213 Inline functions........................272 Elimination of the definition block215 Inlines inside classes.......................273 for loops.........................................217 Access functions.............................274 Storage allocation...........................218 Stash & Stack with inlines.......280 Stash with constructors and Inlines & the compiler.............280 destructors................................219 Limitations.....................................280 Stack with constructors & Order of evaluation.........................281 destructors................................222 Hidden activities in constructors & destructors......................................282 Aggregate initialization............225 Forward referencing.................283 Default constructors.................227 Reducing clutter.......................283 Summary..................................228 More preprocessor features......284 Exercises..................................228 Token pasting.................................285 Improved error checking..........285 7: Function overloading & Summary..................................288 default arguments 229 Exercises..................................288 More name decoration..............230 10: Name control 291 Overloading on return values.........231 Type-safe linkage...........................231 Static elements from C.............291 Overloading example...............232 static variables inside functions.....291 Default arguments....................235 Controlling linkage.........................296 unions.......................................237 Other storage class specifiers..........297 Namespaces.............................297 Summary..................................239 Creating a namespace.....................298 Exercises..................................241 Using a namespace.........................299 Static members in C++.............303 8: Constants 243 Defining storage for static data members.........................................303 Value substitution.....................243 Nested and local classes.................306 const in header files.......................244 static member functions.................307 Safety consts..................................244 Static initialization dependency309 Aggregates.....................................245 What to do......................................310 Differences with C..........................246 Alternate linkage specifications313 Pointers.....................................247 Summary..................................314 Pointer to const..............................248 const pointer...................................248 Exercises..................................314 Assignment and type checking.......249 11: References & the copy- Function arguments & return values........................................250 constructor 315 Passing by const value...................250 Returning by const value................251 Pointers in C++........................315 Passing and returning addresses.....253 References in C++...................316 Classes......................................256 References in functions..................316 const and enum in classes..............256 Argument-passing guidelines.........319 Compile-time constants in classes..258 The copy-constructor...............319 const objects & member functions.260 Passing & returning by value..........319 ROMability....................................264 Copy-construction..........................324 volatile.....................................265 Default copy-constructor................329 Summary..................................266