Ivor Horton's Beginning ANSI C++: The Complete Language, Third Edition IVORHORTON APress Media, LLC Ivor Horton's Beginning ANSI C++: The Complete Language, Third Edition Copyright ©2004 by Ivor Horton Originally published by Apress in 2004 All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN 978-1-59059-227-4 ISBN 978-1-4302-0656-9 (eBook) DOI 10.1007/978-1-4302-0656-9 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Technical Reviewer: Gabriel Dos Reis Editorial Board: Steve Anglin, Dan Appleman, Gary Cornell, James Cox, Tony Davis, John Franklin, Chris Mills, Steven Rycroft, Dominic Shakeshaft, Julian Skinner, Martin Streicher, Jim Sumser, Karen Watterson, Gavin Wray, John Zukowski Assistant Publisher and Project Manager: Grace Wong Copy Manager: Nicole LeClerc Copy Editor: Rebecca Rider Production Manager: Karl Brooks Production Editor: Janet Vaii Proofreader: Lori Bring Compositor: Diana Van Wmkle, Van Winkle Design Cover Designer: Kurt Krames Manufacturing Manager: Tom Debolski The information in this book is distributed on an "as is" basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shaU have any liability to any person or entity with respect to any 10ss or damage caused or aUeged to be caused directly or indirectly by the information contained in this work. Contents at a Glance About the Author ................................................................................................. xix About the Technical Reviewer ........................................................................ xxi Acknowledgments ................................................................................................. xxiii Introduction ......................................................................................................... xxv Chapter 1 Basic Ideas ...................................................................................... 1 Chapter 2 Basic Data Types and Calculations ...................................... 35 Chapter 3 More on Handling Basic Data Types ...................................... 91 Chapter 4 Choices and Decisions in Your Programs .......................... 139 Chapter 5 Loops: Repeating One or More Statements ........................ 177 Chapter 6 Arrays and Strings .................................................................... 215 Chapter 7 Pointers ........................................................................................ 279 Chapter 8 Programming with Functions ................................................... 329 Chapter 9 More on Functions ...................................................................... 377 Chapter 10 Program Files and Preprocessing Directives .................. 419 Chapter 11 Creating Your Own Data Types .............................................. .481 Chapter 12 Classes: Defining Your Own Data Types ............................ 515 Chapter 13 Class Operations ........................................................................ 577 Chapter 14 Operator Overloading ............................................................... 617 Chapter 15 Inheritance .................................................................................. 667 Chapter 16 Virtual Functions and Polymorphism .................................. 715 Chapter 17 Program Errors and Exception Handling ............................ 771 Chapter 18 Using Class Templates To Create Families of Classes .. 811 Chapter 19 Input and Output Operations ................................................. 863 Chapter 20 Introducing the Standard Template Library .................... 939 Appendix A ASCII Codes ................................................................................ 1009 Appendix B C++ Keywords .............................................................................. 1013 Appendix C Standard Library Headers ..................................................... 1015 Appendix D Operator Precedence and Associativity .......................... 1021 Appendix E Understanding Binary and Hexadecimal Numbers ........... 1025 Appendix F Example Project ........................................................................ 1033 Index ..................................................................................................................... 1039 iii Contents About the Author ................................................................................................. xix About the Technical Reviewer ........................................................................ xxi Acknowledgments ................................................................................................. xxiii Introduction ......................................................................................................... xxv Chapter 1 Basic Ideas ............................................................................. 1 Programming Languages .......................................................................................... 1 A Potted History .................................................................................................. 2 Interpreted vs. Compiled Program Execution .................................................. 3 libraries ............................................................................................................... 4 Why Is C++ Such a Great Language? ................................................................. s The ANSI/ISO Standard for C++ ........................................................................ 5 A Simple C++ Program ............................................................................................ 6 Names .................................................................................................................. B Namespaces ....................................................................................................... 10 Keywords ................................................................................................................... 12 C++ Statements and Statement Blocks .......................................................... 12 Code Presentation Style .................................................................................... 13 Program Structure ................................................................................................ 14 Program Functions and Execution .................................................................. 16 Creating an Executable from Your Source Files ...................................... 16 Compiling .......................................................................................................... 18 Linking ............................................................................................................... 19 C++ Source Characters ........................................................................................ 20 The Universal Character Set ............................................................................. 21 Trigraph Sequences ........................................................................................... 21 Escape Sequences ............................................................................................. 22 Whitespace in Statements ................................................................................ 26 Documenting Your Programs ............................................................................... 27 The Standard Library .......................................................................................... 28 Programming in C++ .............................................................................................. 29 Procedural and Object-Oriented Programming ............................................. 30 Summary .....................................................................................................................3 1 Exercises ................................................................................................................. 32 v Contents Chapter 2 Basic Data Types and Calculations .................. 35 Data and Data Types ............................................................................................ 35 Performing Simple Calculations ..................................................................... 36 Introducing literals .......................................................................................... 36 Integer literals. .................................................................................................. 37 Integer Arithmetic ............................................................................................. 39 Operator Precedence and Associativity. .......................................................... 44 Using Variables .................................................................................................... 46 Variable Names .................................................................................................. 46 Integer Variables ................................................................................................ 47 Integer Variable Types ....................................................................................... 51 Integer Ranges ................................................................................................... 54 The Type of an Integer literal. .......................................................................... 55 The Assignment Operator ................................................................................... 56 Multiple Assignments ....................................................................................... 56 Modifying the Value of a Variable ..................................................................... 58 Incrementing and Decrementing Integers .................................................... 60 Postfix Increment and Decrement Operations ............................................... 61 The const Keyword ................................................................................................ 62 Numerical Functions for Integers ................................................................. 65 Generating Random Numbers ......................................................................... 67 Floating-Point Operations ............................................................................... 70 Floating-Point Data 'I}'pes ................................................................................ 70 Floating-Point Operations ................................................................................ 72 Working with Floating-Point Values ................................................................ 75 Mathematical Functions .................................................................................. 79 Working with Characters ................................................................................... 81 Character literals .............................................................................................. 81 Initializing char Variables ................................................................................. 82 Working with Extended Character Sets ........................................................... 86 Functional Notation for Initial Values .................................................... 87 Summary ..................................................................................................................... BB Exercises ................................................................................................................. B9 Chapter 3 More on Handling Basic Data Types .................. 91 Mixed Expressions ................................................................................................ 91 Assignments and Different Types .................................................................... 93 Explicit Casts ..................................................................................................... 94 Old-Style Casts ................................................................................................... 97 Finding Out About Types ................................................................................... 99 Finding the limits ........................................................................................... lOl Bitwise Operators .............................................................................................. 104 The Bitwise Shift Operators ............................................................................ 105 Logical Operations on Bit Patterns ................................................................ 107 vi Contents Enumerated Data Types ...................................................................................... 119 Anonymous Enumerations ............................................................................ 121 Casting Between Integer and Enumeration TYPes ....................................... 122 Synonyms for Data Types ................................................................................. 124 The Lifetime of a Variable ........................................................................... 126 Automatic Variables ........................................................................................ 126 Positioning Variable Declarations .................................................................. 129 GlobalVariables ............................................................................................... 129 Static Variables ................................................................................................. 133 The volatile Type Modifier ........................................................................... 133 Declaring External Variables ....................................................................... 134 Precedence and Associativity ....................................................................... 135 Summary ................................................................................................................... 136 Exercises ............................................................................................................... 137 Chapter 4 Choices and Decisions in Your Programs ... 139 Comparing Data Values ...................................................................................... 139 Applying the Comparison Operators. ............................................................ 140 Comparing Floating Point Values .................................................................. 143 The if Statement ................................................................................................ 144 Nested if Statements ....................................................................................... 147 The if-else Statement ...................................................................................... 153 Nested if-else Statements ............................................................................... 156 Logical Operators .............................................................................................. 159 Logical AND ..................................................................................................... 160 Logical OR ........................................................................................................ 160 Logical Negation. ............................................................................................. 161 The Conditional Operator ............................................................................... 164 The switch Statement ........................................................................................ 167 Unconditional Branching ................................................................................. 172 Decision Statement Blocks and Variable Scope ...................................... 173 Summary ................................................................................................................... 175 Exercises ............................................................................................................... 176 Chapter 5 Loops: Repeating One or More Statements .. 1n Understanding Loops .......................................................................................... 177 The while Loop .................................................................................................... 179 The do-while Loop .............................................................................................. 182 More Complex while Loop Conditions. ......................................................... 185 The for Loop ........................................................................................................ 185 Loops and Variable Scope ............................................................................... 189 Controlling a for Loop with Floating-Point Values ....................................... 190 Using More Complex Loop Control Expressions .......................................... 195 vii Contents Nested Loops ........................................................................................................ 199 Skipping Loop Iterations ............................................................................... 203 Breaking Out of a Loop .................................................................................... 207 Indefinite Loops .............................................................................................. 207 Summary ................................................................................................................... 213 Exercise·s ............................................................................................................... 214 Chapter 6 Arrays and Strings ....................................................... 215 Data Arrays .......................................................................................................... 215 Using an Array ................................................................................................. 216 Initializing Arrays ............................................................................................ 222 Arrays ofCharacters ........................................................................................ 226 Multidimensional Arrays ................................................................................. 231 Initializing Multidimensional Arrays ............................................................. 234 Multidimensional Character Arrays .............................................................. 238 A Better Class of String ............................................................................... 240 Declaring st:riilg Objects ................................................................................. 241 Operations with String Objects ...................................................................... 243 Accessing Characters in a String .................................................................... 247 Accessing Substrings ....................................................................................... 250 Comparing Strings .......................................................................................... 251 Searching a String. ........................................................................................... 258 Modifying a String ........................................................................................... 268 Arrays of Type string. ..................................................................................... 275 Wide-Character Strings .................................................................................... 276 Summary ................................................................................................................... 276 Exercises ............................................................................................................... 277 Chapter 7 Pointers ................................................................................ 279 What Is a Pointer? ............................................................................................ 279 Declaring a Pointer .......................................................................................... 280 Using Pointers ................................................................................................. 281 Initializing Pointers ...................................................................................... 287 Initializing Pointers to 'J)'pe char ................................................................... 288 Constant Pointers and Pointers to Constants ........................................ 299 Pointers and Arrays .......................................................................................... 302 Pointer Arithmetic ........................................................................................... 302 Using Pointer Notation with an Array Name ................................................ 305 Using Pointers with Multidimensional Arrays .............................................. 309 Operations on C-Style Strings ........................................................................ 312 Dynamic Memory Allocation ............................................................................. 314 The Free Store (aka the Heap) ........................................................................ 316 The Operators new and delete ....................................................................... 316 Dynamic Memory Allocation for Arrays ........................................................ 317 viii Contents Hazards of Dynamic Memory Allocation ...................................................... 320 Converting Pointers ........................................................................................ 326 Summary ................................................................................................................... 327 Exercises ............................................................................................................... 328 Chapter 8 Programming with Functions .................................. 329 Segmenting Your Programs ............................................................................... 329 Why You Should Segment Your Programs into Functions ........................... 331 Understanding Functions ................................................................................. 331 Defining a Function ........................................................................................ 332 Function Declarations .................................................................................... 338 Passing Arguments to a Function ................................................................. 340 The Pass-by-Value Mechanism ...................................................................... 341 The Pass-by-Reference Mechanism ............................................................... 352 Arguments to mainO ....................................................................................... 358 Default Argument Values ................................................................................. 359 Multiple Default Parameter Values ................................................................ 360 Returning Values from a Function ............................................................... 364 Returning a Pointer ......................................................................................... 364 Returning a Reference ..................................................................................... 368 Returning a New Variable from a Function ................................................... 369 Inline Functions ................................................................................................ 369 Static Variables ................................................................................................ 370 Summary ................................................................................................................... 373 Exercises ............................................................................................................... 374 Chapter 9 More on Functions ......................................................... 377 Function Overloading ........................................................................................ 377 The Signature of a Function ........................................................................... 378 Overloading and Pointer Parameters ............................................................ 381 Overloading and Reference Parameters ........................................................ 381 Overloading and const Parameters ............................................................... 384 Overloading and Default Argument Values ................................................... 386 A Sausage Machine for Functions ................................................................. 386 Creating Instances of a Function Template .................................................. 388 Explicitly Specifying a Template Parameter .................................................. 391 Specialization ofTemplates ............................................................................ 392 Function Templates and Overloading ........................................................... 395 Templates with Multiple Parameters ............................................................. 396 Pointers to Functions ...................................................................................... 398 Declaring Pointers to Functions .................................................................... 399 Passing a Function as an Argument ............................................................... 403 Arrays of Pointers to Functions ...................................................................... 405 ix Contents Recursion ...............................................................................................................4 06 Using Recursion .............................................................................................. 409 Summary ...................................................................................................................4 16 Exercises ...............................................................................................................4 17 Chapter 10 Program Files and Preprocessing Directives ....................................... 419 Working with Program Files ...........................................................................4 19 The Scope of a Naiile ...................................................................................... 421 The "One Definition'' Rule .............................................................................. 424 Prograin Files and Linkage ............................................................................. 424 External Naines ............................................................................................... 425 Namespaces .............................................................................................................4 31 The Global Nainespace ................................................................................... 432 Defining a Nai11espace .................................................................................... 433 Functions and Nainespaces ........................................................................... 437 Function Templates and Nainespaces. .......................................................... 441 Extension Nainespaces ................................................................................... 443 Unnained Nainespaces ................................................................................... 447 Nainespace Aliases .......................................................................................... 448 Nested Nainespaces ........................................................................................ 448 Preprocessing Your Source Code ................................................................... 449 Including Header Files in Your Prograins ...................................................... 451 Substitutions in Your Prograin ....................................................................... 452 Macro Substitutions ........................................................................................ 454 Preprocessing Directives on Multiple lines .................................................. 458 Strings As Macro Arguments .......................................................................... 458 Joining the Arguments in a Macro Expansion ............................................. .460 Logical Preprocessing Directives ............................................................... 461 The Logical #if Directive ................................................................................. 461 Directives Testing for Specific Values ............................................................. 464 Multiple Choice Code Selection ..................................................................... 465 Standard Preprocessing Macros. .................................................................... 466 The #error and #pragma Directives ............................................................... 467 Debugging Methods ..............................................................................................4 68 Integrated Debuggers ..................................................................................... 468 Preprocessing Directives in Debugging ........................................................ 469 Using the assertO Macro ................................................................................. 476 Summary ................................................................................................................... 478 Exercises ...............................................................................................................4 79 X
Description: