C++ Primer 0201721481, 9780201721485

"C++ Primeris well known as one of the best books for learning C++ and is useful for C++ programmers of all skill l

381 25 6MB

English Pages 885 [910] Year 2005

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover......Page 1
Contents......Page 8
Preface......Page 20
Chapter 1 Getting Started......Page 24
1.1 Writing a Simple C++ Program......Page 25
1.1.1 Compiling and Executing Our Program......Page 26
1.2 A First Look at Input/Output......Page 28
1.2.2 A Program that Uses the IO Library......Page 29
1.3 A Word About Comments......Page 33
1.4 Control Structures......Page 34
1.4.1 The while Statement......Page 35
1.4.2 The for Statement......Page 37
1.4.3 The if Statement......Page 40
1.4.4 Reading an Unknown Number of Inputs......Page 41
1.5 Introducing Classes......Page 43
1.5.1 The Sales_item Class......Page 44
1.5.2 A First Look at Member Functions......Page 47
1.6 The C++ Program......Page 48
Defined Terms......Page 51
Part I: The Basics......Page 54
Chapter 2 Variables and Basic Types......Page 56
2.1 Primitive Built-in Types......Page 57
2.2 Literal Constants......Page 60
2.3 Variables......Page 66
2.4 const Qualifier......Page 79
2.5 References......Page 81
2.6 Typedef Names......Page 84
2.7 Enumerations......Page 85
2.8 Class Types......Page 86
2.9 Writing Our Own Header Files......Page 90
Defined Terms......Page 96
Chapter 3 Library Types......Page 100
3.1 Namespace using Declarations......Page 101
3.2 Library string Type......Page 103
3.3 Library vector Type......Page 113
3.4 Introducing Iterators......Page 118
3.5 Library bitset Type......Page 124
Defined Terms......Page 130
Chapter 4 Arrays and Pointers......Page 132
4.1 Arrays......Page 133
4.2 Introducing Pointers......Page 137
4.3 C-Style Character Strings......Page 153
4.4 Multidimensioned Arrays......Page 164
Defined Terms......Page 168
Chapter 5 Expressions......Page 170
5.1 Arithmetic Operators......Page 172
5.2 Relational and Logical Operators......Page 175
5.3 The Bitwise Operators......Page 177
5.4 Assignment Operators......Page 182
5.5 Increment and Decrement Operators......Page 185
5.6 The Arrow Operator......Page 187
5.7 The Conditional Operator......Page 188
5.8 The sizeof Operator......Page 190
5.10 Evaluating Compound Expressions......Page 191
5.11 The new and delete Expressions......Page 197
5.12 Type Conversions......Page 201
Defined Terms......Page 211
Chapter 6 Statements......Page 214
6.1 Simple Statements......Page 215
6.3 Compound Statements (Blocks)......Page 216
6.4 Statement Scope......Page 217
6.5 The if Statement......Page 218
6.6 The switch Statement......Page 222
6.7 The while Statement......Page 227
6.8 The for Loop Statement......Page 230
6.9 The do while Statement......Page 233
6.10 The break Statement......Page 235
6.12 The goto Statement......Page 237
6.13 try Blocks and Exception Handling......Page 238
6.14 Using the Preprocessor for Debugging......Page 243
Defined Terms......Page 246
Chapter 7 Functions......Page 248
7.1 Defining a Function......Page 249
7.2 Argument Passing......Page 252
7.3 The return Statement......Page 268
7.4 Function Declarations......Page 274
7.5 Local Objects......Page 277
7.6 Inline Functions......Page 279
7.7 Class Member Functions......Page 281
7.8 Overloaded Functions......Page 288
7.9 Pointers to Functions......Page 299
Defined Terms......Page 303
Chapter 8 The IO Library......Page 306
8.1 An Object-Oriented Library......Page 307
8.2 Condition States......Page 310
8.3 Managing the Output Buffer......Page 313
8.4 File Input and Output......Page 316
8.5 String Streams......Page 322
Defined Terms......Page 325
Part II: Containers and Algorithms......Page 326
Chapter 9 Sequential Containers......Page 328
9.1 Defining a Sequential Container......Page 330
9.2 Iterators and Iterator Ranges......Page 334
9.3 Sequence Container Operations......Page 339
9.4 How a vector Grows......Page 353
9.5 Deciding Which Container to Use......Page 356
9.6 strings Revisited......Page 358
9.7 Container Adaptors......Page 371
Defined Terms......Page 376
Chapter 10 Associative Containers......Page 378
10.1 Preliminaries: the pair Type......Page 379
10.2 Associative Containers......Page 381
10.3 The map Type......Page 383
10.4 The set Type......Page 395
10.5 The multimap and multiset Types......Page 398
10.6 Using Containers: Text-Query Program......Page 402
Defined Terms......Page 411
Chapter 11 Generic Algorithms......Page 414
11.1 Overview......Page 415
11.2 A First Look at the Algorithms......Page 418
11.3 Revisiting Iterators......Page 428
11.4 Structure of Generic Algorithms......Page 442
11.5 Container-Specific Algorithms......Page 444
Defined Terms......Page 447
Part III: Classes and Data Abstraction......Page 450
Chapter 12 Classes......Page 452
12.1 Class Definitions and Declarations......Page 453
12.2 The Implicit this Pointer......Page 463
12.3 Class Scope......Page 467
12.4 Constructors......Page 474
12.5 Friends......Page 488
12.6 static Class Members......Page 490
Defined Terms......Page 496
Chapter 13 Copy Control......Page 498
13.1 The Copy Constructor......Page 499
13.2 The Assignment Operator......Page 505
13.3 The Destructor......Page 507
13.4 A Message-Handling Example......Page 509
13.5 Managing Pointer Members......Page 515
Defined Terms......Page 525
Chapter 14 Overloaded Operations and Conversions......Page 528
14.1 Defining an Overloaded Operator......Page 529
14.2 Input and Output Operators......Page 536
14.3 Arithmetic and Relational Operators......Page 540
14.4 Assignment Operators......Page 543
14.5 Subscript Operator......Page 545
14.6 Member Access Operators......Page 546
14.7 Increment and Decrement Operators......Page 549
14.8 Call Operator and Function Objects......Page 553
14.9 Conversions and Class Types......Page 558
Defined Terms......Page 575
Part IV: Object-Oriented and Generic Programming......Page 578
Chapter 15 Object-Oriented Programming......Page 580
15.1 OOP: An Overview......Page 581
15.2 Defining Base and Derived Classes......Page 583
15.3 Conversions and Inheritance......Page 600
15.4 Constructors and Copy Control......Page 603
15.5 Class Scope under Inheritance......Page 613
15.6 Pure Virtual Functions......Page 618
15.7 Containers and Inheritance......Page 620
15.8 Handle Classes and Inheritance......Page 621
15.9 Text Queries Revisited......Page 630
Defined Terms......Page 644
Chapter 16 Templates and Generic Programming......Page 646
16.1 Template Definitions......Page 647
16.2 Instantiation......Page 659
16.3 Template Compilation Models......Page 666
16.4 Class Template Members......Page 670
16.5 A Generic Handle Class......Page 689
16.6 Template Specializations......Page 694
16.7 Overloading and Function Templates......Page 702
Defined Terms......Page 706
Part V: Advanced Topics......Page 708
Chapter 17 Tools for Large Programs......Page 710
17.1 Exception Handling......Page 711
17.2 Namespaces......Page 735
17.3 Multiple and Virtual Inheritance......Page 754
Defined Terms......Page 771
Chapter 18 Specialized Tools and Techniques......Page 776
18.1 Optimizing Memory Allocation......Page 777
18.2 Run-Time Type Identification......Page 795
18.3 Pointer to Class Member......Page 803
18.4 Nested Classes......Page 809
18.5 Union: A Space-Saving Class......Page 815
18.6 Local Classes......Page 819
18.7 Inherently Nonportable Features......Page 820
Defined Terms......Page 828
Appendix A: The Library......Page 832
A.1 Library Names and Headers......Page 833
A.2.1 Algorithms to Find an Object......Page 834
A.2.2 Other Read-Only Algorithms......Page 836
A.2.3 Binary-Search Algorithms......Page 837
A.2.4 Algorithms that Write Container Elements......Page 838
A.2.5 Partitioning and Sorting Algorithms......Page 840
A.2.6 General Reordering Operations......Page 841
A.2.7 Permutation Algorithms......Page 843
A.2.8 Set Algorithms for Sorted Sequences......Page 844
A.2.9 Minimum and Maximum Values......Page 845
A.2.10 Numeric Algorithms......Page 846
A.3.2 Many Manipulators Change the Format State......Page 848
A.3.3 Controlling Output Formats......Page 849
A.3.4 Controlling Input Formatting......Page 856
A.3.6 Single-Byte Operations......Page 857
A.3.7 Multi-Byte Operations......Page 858
A.3.8 Random Access to a Stream......Page 860
A.3.9 Reading and Writing to the Same File......Page 863
Index......Page 866
A......Page 867
B......Page 870
C......Page 871
D......Page 876
E......Page 879
F......Page 880
H......Page 883
I......Page 884
K......Page 886
L......Page 887
M......Page 888
N......Page 891
O......Page 892
P......Page 895
R......Page 898
S......Page 900
T......Page 904
U......Page 905
V......Page 906
W......Page 907
Z......Page 908
Recommend Papers

C++ Primer
 0201721481, 9780201721485

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

C++ Primer Fourth Edition

This page intentionally left blank

C++ Primer Fourth Edition

Stanley B. Lippman Josée Lajoie Barbara E. Moo

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sidney • Tokyo • Singapore • Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U. S. Corporate and Government Sales (800) 382-3419 [email protected] For sales outside the U. S., please contact: International Sales [email protected] Visit us on the Web: www.awprofessional.com Library of Congress Cataloging-in-Publication Data Lippman, Stanley B. C++ primer / Stanley B. Lippman, Josée Lajoie, Barbara E. Moo. — 4th ed. p. cm. Includes index. ISBN 0-201-72148-1 (pbk. : alk. paper) 1. C++ (Computer program language) I. Lajoie, Josée. II. Moo, Barbara E. III. Title. QA76.73.C153L57697 2005 005.13’3–dc22

2004029301

c 2005 Objectwrite Inc., Josée Lajoie and Barbara E. Moo Copyright  All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: Pearson Education, Inc. Rights and Contracts Department One Lake Street Upper Saddle River, NJ 07458 ISBN 0-201-72148-1 Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts. First printing, February 2005

To Beth, who makes this, and all things, possible. —— To Daniel and Anna, who contain virtually all possiblities. —SBL

To Mark and Mom, for their unconditional love and support. —JL

To Andy, who taught me to program and so much more. —BEM

This page intentionally left blank

Contents Preface

xix

Chapter 1 Getting Started 1.1 Writing a Simple C++ Program . . . . . . . . . . 1.1.1 Compiling and Executing Our Program . 1.2 A First Look at Input/Output . . . . . . . . . . . 1.2.1 Standard Input and Output Objects . . . 1.2.2 A Program that Uses the IO Library . . . 1.3 A Word About Comments . . . . . . . . . . . . . 1.4 Control Structures . . . . . . . . . . . . . . . . . . 1.4.1 The while Statement . . . . . . . . . . . 1.4.2 The for Statement . . . . . . . . . . . . . 1.4.3 The if Statement . . . . . . . . . . . . . . 1.4.4 Reading an Unknown Number of Inputs 1.5 Introducing Classes . . . . . . . . . . . . . . . . . 1.5.1 The Sales_item Class . . . . . . . . . . 1.5.2 A First Look at Member Functions . . . . 1.6 The C++ Program . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

Part I The Basics

1 2 3 5 6 6 10 11 12 14 17 18 20 21 24 25 28 28

31

Chapter 2 Variables and Basic Types 2.1 Primitive Built-in Types . . . . . . . 2.1.1 Integral Types . . . . . . . . . 2.1.2 Floating-Point Types . . . . . 2.2 Literal Constants . . . . . . . . . . . 2.3 Variables . . . . . . . . . . . . . . . . 2.3.1 What Is a Variable? . . . . . . 2.3.2 The Name of a Variable . . . 2.3.3 Defining Objects . . . . . . . 2.3.4 Variable Initialization Rules . 2.3.5 Declarations and Definitions vii

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

33 34 34 37 37 43 45 46 48 50 52

viii

Contents 2.3.6 Scope of a Name . . . . . . . . . . . . . 2.3.7 Define Variables Where They Are Used 2.4 const Qualifier . . . . . . . . . . . . . . . . . . 2.5 References . . . . . . . . . . . . . . . . . . . . . 2.6 Typedef Names . . . . . . . . . . . . . . . . . . 2.7 Enumerations . . . . . . . . . . . . . . . . . . . 2.8 Class Types . . . . . . . . . . . . . . . . . . . . . 2.9 Writing Our Own Header Files . . . . . . . . . 2.9.1 Designing Our Own Headers . . . . . . 2.9.2 A Brief Introduction to the Preprocessor Chapter Summary . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

54 55 56 58 61 62 63 67 67 69 73 73

Chapter 3 Library Types 3.1 Namespace using Declarations . . . . . . . . . . 3.2 Library string Type . . . . . . . . . . . . . . . . 3.2.1 Defining and Initializing strings . . . . 3.2.2 Reading and Writing strings . . . . . . 3.2.3 Operations on strings . . . . . . . . . . 3.2.4 Dealing with the Characters of a string 3.3 Library vector Type . . . . . . . . . . . . . . . . 3.3.1 Defining and Initializing vectors . . . . 3.3.2 Operations on vectors . . . . . . . . . . 3.4 Introducing Iterators . . . . . . . . . . . . . . . . 3.4.1 Iterator Arithmetic . . . . . . . . . . . . . 3.5 Library bitset Type . . . . . . . . . . . . . . . . 3.5.1 Defining and Initializing bitsets . . . . 3.5.2 Operations on bitsets . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

77 78 80 80 81 83 88 90 91 93 95 100 101 102 104 107 107

Chapter 4 Arrays and Pointers 4.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . . 4.1.1 Defining and Initializing Arrays . . . . . 4.1.2 Operations on Arrays . . . . . . . . . . . 4.2 Introducing Pointers . . . . . . . . . . . . . . . . 4.2.1 What Is a Pointer? . . . . . . . . . . . . . 4.2.2 Defining and Initializing Pointers . . . . 4.2.3 Operations on Pointers . . . . . . . . . . . 4.2.4 Using Pointers to Access Array Elements 4.2.5 Pointers and the const Qualifier . . . . . 4.3 C-Style Character Strings . . . . . . . . . . . . . . 4.3.1 Dynamically Allocating Arrays . . . . . . 4.3.2 Interfacing to Older Code . . . . . . . . . 4.4 Multidimensioned Arrays . . . . . . . . . . . . . 4.4.1 Pointers and Multidimensioned Arrays . Chapter Summary . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

109 110 110 113 114 115 116 119 122 126 130 134 139 141 143 145

Contents

ix

Defined Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Chapter 5 Expressions 5.1 Arithmetic Operators . . . . . . . . . . . . . . . . 5.2 Relational and Logical Operators . . . . . . . . . 5.3 The Bitwise Operators . . . . . . . . . . . . . . . 5.3.1 Using bitset Objects or Integral Values 5.3.2 Using the Shift Operators for IO . . . . . 5.4 Assignment Operators . . . . . . . . . . . . . . . 5.4.1 Assignment Is Right Associative . . . . . 5.4.2 Assignment Has Low Precedence . . . . 5.4.3 Compound Assignment Operators . . . . 5.5 Increment and Decrement Operators . . . . . . . 5.6 The Arrow Operator . . . . . . . . . . . . . . . . 5.7 The Conditional Operator . . . . . . . . . . . . . 5.8 The sizeof Operator . . . . . . . . . . . . . . . 5.9 Comma Operator . . . . . . . . . . . . . . . . . . 5.10 Evaluating Compound Expressions . . . . . . . . 5.10.1 Precedence . . . . . . . . . . . . . . . . . . 5.10.2 Associativity . . . . . . . . . . . . . . . . 5.10.3 Order of Evaluation . . . . . . . . . . . . 5.11 The new and delete Expressions . . . . . . . . 5.12 Type Conversions . . . . . . . . . . . . . . . . . . 5.12.1 When Implicit Type Conversions Occur . 5.12.2 The Arithmetic Conversions . . . . . . . 5.12.3 Other Implicit Conversions . . . . . . . . 5.12.4 Explicit Conversions . . . . . . . . . . . . 5.12.5 When Casts Might Be Useful . . . . . . . 5.12.6 Named Casts . . . . . . . . . . . . . . . . 5.12.7 Old-Style Casts . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

147 149 152 154 156 158 159 160 160 161 162 164 165 167 168 168 168 170 172 174 178 179 180 181 183 184 184 186 188 188

Chapter 6 Statements 6.1 Simple Statements . . . . . . . . . . . . . . . . 6.2 Declaration Statements . . . . . . . . . . . . . 6.3 Compound Statements (Blocks) . . . . . . . . 6.4 Statement Scope . . . . . . . . . . . . . . . . . 6.5 The if Statement . . . . . . . . . . . . . . . . 6.5.1 The if Statement else Branch . . . . 6.6 The switch Statement . . . . . . . . . . . . . 6.6.1 Using a switch . . . . . . . . . . . . . 6.6.2 Control Flow within a switch . . . . 6.6.3 The default Label . . . . . . . . . . 6.6.4 switch Expression and Case Labels . 6.6.5 Variable Definitions inside a switch 6.7 The while Statement . . . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

. . . . . . . . . . . . .

191 192 193 193 194 195 197 199 200 201 203 203 204 204

. . . . . . . . . . . . .

. . . . . . . . . . . . .

x

Contents 6.8

The for Loop Statement . . . . . . . . . . . . . 6.8.1 Omitting Parts of the for Header . . . 6.8.2 Multiple Definitions in the for Header 6.9 The do while Statement . . . . . . . . . . . . . 6.10 The break Statement . . . . . . . . . . . . . . . 6.11 The continue Statement . . . . . . . . . . . . 6.12 The goto Statement . . . . . . . . . . . . . . . 6.13 try Blocks and Exception Handling . . . . . . 6.13.1 A throw Expression . . . . . . . . . . . 6.13.2 The try Block . . . . . . . . . . . . . . . 6.13.3 Standard Exceptions . . . . . . . . . . . 6.14 Using the Preprocessor for Debugging . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

207 209 210 210 212 214 214 215 216 217 219 220 223 223

Chapter 7 Functions 7.1 Defining a Function . . . . . . . . . . . . . . . . . . . . . 7.1.1 Function Return Type . . . . . . . . . . . . . . . 7.1.2 Function Parameter List . . . . . . . . . . . . . . 7.2 Argument Passing . . . . . . . . . . . . . . . . . . . . . 7.2.1 Nonreference Parameters . . . . . . . . . . . . . 7.2.2 Reference Parameters . . . . . . . . . . . . . . . 7.2.3 vector and Other Container Parameters . . . . 7.2.4 Array Parameters . . . . . . . . . . . . . . . . . . 7.2.5 Managing Arrays Passed to Functions . . . . . . 7.2.6 main: Handling Command-Line Options . . . . 7.2.7 Functions with Varying Parameters . . . . . . . 7.3 The return Statement . . . . . . . . . . . . . . . . . . . 7.3.1 Functions with No Return Value . . . . . . . . . 7.3.2 Functions that Return a Value . . . . . . . . . . . 7.3.3 Recursion . . . . . . . . . . . . . . . . . . . . . . 7.4 Function Declarations . . . . . . . . . . . . . . . . . . . 7.4.1 Default Arguments . . . . . . . . . . . . . . . . . 7.5 Local Objects . . . . . . . . . . . . . . . . . . . . . . . . . 7.5.1 Automatic Objects . . . . . . . . . . . . . . . . . 7.5.2 Static Local Objects . . . . . . . . . . . . . . . . . 7.6 Inline Functions . . . . . . . . . . . . . . . . . . . . . . . 7.7 Class Member Functions . . . . . . . . . . . . . . . . . . 7.7.1 Defining the Body of a Member Function . . . . 7.7.2 Defining a Member Function Outside the Class 7.7.3 Writing the Sales_item Constructor . . . . . . 7.7.4 Organizing Class Code Files . . . . . . . . . . . 7.8 Overloaded Functions . . . . . . . . . . . . . . . . . . . 7.8.1 Overloading and Scope . . . . . . . . . . . . . . 7.8.2 Function Matching and Argument Conversions 7.8.3 The Three Steps in Overload Resolution . . . . . 7.8.4 Argument-Type Conversions . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

225 226 227 228 229 230 232 237 238 241 243 244 245 245 246 249 251 253 254 255 255 256 258 259 261 262 264 265 268 269 270 272

Contents

xi

7.9 Pointers to Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Defined Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Chapter 8 The IO Library 8.1 An Object-Oriented Library . . . . . . . . . . . . . 8.2 Condition States . . . . . . . . . . . . . . . . . . . . 8.3 Managing the Output Buffer . . . . . . . . . . . . . 8.4 File Input and Output . . . . . . . . . . . . . . . . 8.4.1 Using File Stream Objects . . . . . . . . . . 8.4.2 File Modes . . . . . . . . . . . . . . . . . . . 8.4.3 A Program to Open and Check Input Files 8.5 String Streams . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

Part II Containers and Algorithms Chapter 9 Sequential Containers 9.1 Defining a Sequential Container . . . . . . . . . . . . . . 9.1.1 Initializing Container Elements . . . . . . . . . . 9.1.2 Constraints on Types that a Container Can Hold 9.2 Iterators and Iterator Ranges . . . . . . . . . . . . . . . . 9.2.1 Iterator Ranges . . . . . . . . . . . . . . . . . . . 9.2.2 Some Container Operations Invalidate Iterators 9.3 Sequence Container Operations . . . . . . . . . . . . . . 9.3.1 Container Typedefs . . . . . . . . . . . . . . . . . 9.3.2 begin and end Members . . . . . . . . . . . . . 9.3.3 Adding Elements to a Sequential Container . . . 9.3.4 Relational Operators . . . . . . . . . . . . . . . . 9.3.5 Container Size Operations . . . . . . . . . . . . . 9.3.6 Accessing Elements . . . . . . . . . . . . . . . . . 9.3.7 Erasing Elements . . . . . . . . . . . . . . . . . . 9.3.8 Assignment and swap . . . . . . . . . . . . . . . 9.4 How a vector Grows . . . . . . . . . . . . . . . . . . . 9.4.1 capacity and reserve Members . . . . . . . 9.5 Deciding Which Container to Use . . . . . . . . . . . . . 9.6 strings Revisited . . . . . . . . . . . . . . . . . . . . . 9.6.1 Other Ways to Construct strings . . . . . . . . 9.6.2 Other Ways to Change a string . . . . . . . . . 9.6.3 string-Only Operations . . . . . . . . . . . . . 9.6.4 string Search Operations . . . . . . . . . . . . 9.6.5 Comparing strings . . . . . . . . . . . . . . . . 9.7 Container Adaptors . . . . . . . . . . . . . . . . . . . . . 9.7.1 Stack Adaptor . . . . . . . . . . . . . . . . . . . . 9.7.2 Queue and Priority Queue . . . . . . . . . . . . .

283 284 287 290 293 293 296 299 299 302 302

303 . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . .

305 307 307 309 311 314 315 316 316 317 318 321 323 324 326 328 330 331 333 335 338 339 341 343 346 348 350 351

xii

Contents Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 Defined Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 Chapter 10 Associative Containers 10.1 Preliminaries: the pair Type . . . . . . . . . . . . . . . 10.2 Associative Containers . . . . . . . . . . . . . . . . . . . 10.3 The map Type . . . . . . . . . . . . . . . . . . . . . . . . 10.3.1 Defining a map . . . . . . . . . . . . . . . . . . . 10.3.2 Types Defined by map . . . . . . . . . . . . . . . 10.3.3 Adding Elements to a map . . . . . . . . . . . . . 10.3.4 Subscripting a map . . . . . . . . . . . . . . . . . 10.3.5 Using map::insert . . . . . . . . . . . . . . . . 10.3.6 Finding and Retrieving a map Element . . . . . . 10.3.7 Erasing Elements from a map . . . . . . . . . . . 10.3.8 Iterating across a map . . . . . . . . . . . . . . . 10.3.9 A Word Transformation Map . . . . . . . . . . . 10.4 The set Type . . . . . . . . . . . . . . . . . . . . . . . . 10.4.1 Defining and Using sets . . . . . . . . . . . . . 10.4.2 Building a Word-Exclusion Set . . . . . . . . . . 10.5 The multimap and multiset Types . . . . . . . . . . 10.5.1 Adding and Removing Elements . . . . . . . . . 10.5.2 Finding Elements in a multimap or multiset 10.6 Using Containers: Text-Query Program . . . . . . . . . 10.6.1 Design of the Query Program . . . . . . . . . . . 10.6.2 TextQuery Class . . . . . . . . . . . . . . . . . . 10.6.3 Using the TextQuery Class . . . . . . . . . . . 10.6.4 Writing the Member Functions . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

355 356 358 360 360 361 362 362 364 367 368 369 369 372 373 374 375 376 376 379 380 382 383 385 388 388

Chapter 11 Generic Algorithms 11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 A First Look at the Algorithms . . . . . . . . . . . . 11.2.1 Read-Only Algorithms . . . . . . . . . . . . . 11.2.2 Algorithms that Write Container Elements . 11.2.3 Algorithms that Reorder Container Elements 11.3 Revisiting Iterators . . . . . . . . . . . . . . . . . . . 11.3.1 Insert Iterators . . . . . . . . . . . . . . . . . 11.3.2 iostream Iterators . . . . . . . . . . . . . . 11.3.3 Reverse Iterators . . . . . . . . . . . . . . . . 11.3.4 const Iterators . . . . . . . . . . . . . . . . . 11.3.5 The Five Iterator Categories . . . . . . . . . . 11.4 Structure of Generic Algorithms . . . . . . . . . . . 11.4.1 Algorithm Parameter Patterns . . . . . . . . 11.4.2 Algorithm Naming Conventions . . . . . . . 11.5 Container-Specific Algorithms . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

391 392 395 396 398 400 405 406 407 412 415 416 419 419 420 421 424

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

Contents

xiii

Defined Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424

Part III Classes and Data Abstraction

427

Chapter 12 Classes 12.1 Class Definitions and Declarations . . . . . . . 12.1.1 Class Definitions: A Recap . . . . . . . 12.1.2 Data Abstraction and Encapsulation . . 12.1.3 More on Class Definitions . . . . . . . . 12.1.4 Class Declarations versus Definitions . 12.1.5 Class Objects . . . . . . . . . . . . . . . 12.2 The Implicit this Pointer . . . . . . . . . . . . 12.3 Class Scope . . . . . . . . . . . . . . . . . . . . . 12.3.1 Name Lookup in Class Scope . . . . . . 12.4 Constructors . . . . . . . . . . . . . . . . . . . . 12.4.1 The Constructor Initializer . . . . . . . . 12.4.2 Default Arguments and Constructors . 12.4.3 The Default Constructor . . . . . . . . . 12.4.4 Implicit Class-Type Conversions . . . . 12.4.5 Explicit Initialization of Class Members 12.5 Friends . . . . . . . . . . . . . . . . . . . . . . . 12.6 static Class Members . . . . . . . . . . . . . 12.6.1 static Member Functions . . . . . . . 12.6.2 static Data Members . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

429 430 430 432 434 437 439 440 444 447 451 453 458 458 461 464 465 467 469 469 473 473

Chapter 13 Copy Control 13.1 The Copy Constructor . . . . . . . . . . . . . 13.1.1 The Synthesized Copy Constructor . . 13.1.2 Defining Our Own Copy Constructor 13.1.3 Preventing Copies . . . . . . . . . . . 13.2 The Assignment Operator . . . . . . . . . . . 13.3 The Destructor . . . . . . . . . . . . . . . . . . 13.4 A Message-Handling Example . . . . . . . . 13.5 Managing Pointer Members . . . . . . . . . . 13.5.1 Defining Smart Pointer Classes . . . . 13.5.2 Defining Valuelike Classes . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

475 476 479 480 481 482 484 486 492 495 499 502 502

Chapter 14 Overloaded Operations and Conversions 14.1 Defining an Overloaded Operator . . . . . . . 14.1.1 Overloaded Operator Design . . . . . . 14.2 Input and Output Operators . . . . . . . . . . . 14.2.1 Overloading the Output Operator > . . . . . . . . 14.3 Arithmetic and Relational Operators . . . . . . . . . . . . 14.3.1 Equality Operators . . . . . . . . . . . . . . . . . . 14.3.2 Relational Operators . . . . . . . . . . . . . . . . . 14.4 Assignment Operators . . . . . . . . . . . . . . . . . . . . 14.5 Subscript Operator . . . . . . . . . . . . . . . . . . . . . . 14.6 Member Access Operators . . . . . . . . . . . . . . . . . . 14.7 Increment and Decrement Operators . . . . . . . . . . . . 14.8 Call Operator and Function Objects . . . . . . . . . . . . . 14.8.1 Using Function Objects with Library Algorithms . 14.8.2 Library-Defined Function Objects . . . . . . . . . 14.8.3 Function Adaptors for Function Objects . . . . . . 14.9 Conversions and Class Types . . . . . . . . . . . . . . . . 14.9.1 Why Conversions Are Useful . . . . . . . . . . . . 14.9.2 Conversion Operators . . . . . . . . . . . . . . . . 14.9.3 Argument Matching and Conversions . . . . . . . 14.9.4 Overload Resolution and Class Arguments . . . . 14.9.5 Overloading, Conversions, and Operators . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

Part IV Object-Oriented and Generic Programming Chapter 15 Object-Oriented Programming 15.1 OOP: An Overview . . . . . . . . . . . . . . . . . . 15.2 Defining Base and Derived Classes . . . . . . . . . 15.2.1 Defining a Base Class . . . . . . . . . . . . . 15.2.2 protected Members . . . . . . . . . . . . 15.2.3 Derived Classes . . . . . . . . . . . . . . . . 15.2.4 virtual and Other Member Functions . . 15.2.5 Public, Private, and Protected Inheritance . 15.2.6 Friendship and Inheritance . . . . . . . . . 15.2.7 Inheritance and Static Members . . . . . . 15.3 Conversions and Inheritance . . . . . . . . . . . . 15.3.1 Derived-to-Base Conversions . . . . . . . . 15.3.2 Conversions from Base to Derived . . . . . 15.4 Constructors and Copy Control . . . . . . . . . . . 15.4.1 Base-Class Constructors and Copy Control 15.4.2 Derived-Class Constructors . . . . . . . . . 15.4.3 Copy Control and Inheritance . . . . . . . . 15.4.4 Virtual Destructors . . . . . . . . . . . . . . 15.4.5 Virtuals in Constructors and Destructors . 15.5 Class Scope under Inheritance . . . . . . . . . . . . 15.5.1 Name Lookup Happens at Compile Time . 15.5.2 Name Collisions and Inheritance . . . . . . 15.5.3 Scope and Member Functions . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

515 517 518 520 520 522 523 526 530 531 533 535 535 536 537 541 544 547 552 552

555 . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

557 558 560 560 562 563 566 570 575 576 577 577 580 580 580 581 584 587 589 590 590 591 592

Contents 15.5.4 Virtual Functions and Scope . 15.6 Pure Virtual Functions . . . . . . . . 15.7 Containers and Inheritance . . . . . 15.8 Handle Classes and Inheritance . . . 15.8.1 A Pointerlike Handle . . . . . 15.8.2 Cloning an Unknown Type . 15.8.3 Using the Handle . . . . . . . 15.9 Text Queries Revisited . . . . . . . . 15.9.1 An Object-Oriented Solution 15.9.2 A Valuelike Handle . . . . . . 15.9.3 The Query_base Class . . . 15.9.4 The Query Handle Class . . 15.9.5 The Derived Classes . . . . . 15.9.6 The eval Functions . . . . . Chapter Summary . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . .

xv . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

594 595 597 598 599 602 603 607 609 610 612 613 616 618 621 621

Chapter 16 Templates and Generic Programming 16.1 Template Definitions . . . . . . . . . . . . . . . . . . . 16.1.1 Defining a Function Template . . . . . . . . . . 16.1.2 Defining a Class Template . . . . . . . . . . . . 16.1.3 Template Parameters . . . . . . . . . . . . . . . 16.1.4 Template Type Parameters . . . . . . . . . . . . 16.1.5 Nontype Template Parameters . . . . . . . . . 16.1.6 Writing Generic Programs . . . . . . . . . . . . 16.2 Instantiation . . . . . . . . . . . . . . . . . . . . . . . . 16.2.1 Template Argument Deduction . . . . . . . . . 16.2.2 Function-Template Explicit Arguments . . . . 16.3 Template Compilation Models . . . . . . . . . . . . . . 16.4 Class Template Members . . . . . . . . . . . . . . . . . 16.4.1 Class-Template Member Functions . . . . . . . 16.4.2 Template Arguments for Nontype Parameters 16.4.3 Friend Declarations in Class Templates . . . . 16.4.4 Queue and QueueItem Friend Declarations . 16.4.5 Member Templates . . . . . . . . . . . . . . . . 16.4.6 The Complete Queue Class . . . . . . . . . . . 16.4.7 static Members of Class Templates . . . . . 16.5 A Generic Handle Class . . . . . . . . . . . . . . . . . 16.5.1 Defining the Handle Class . . . . . . . . . . . . 16.5.2 Using the Handle . . . . . . . . . . . . . . . . . 16.6 Template Specializations . . . . . . . . . . . . . . . . . 16.6.1 Specializing a Function Template . . . . . . . . 16.6.2 Specializing a Class Template . . . . . . . . . . 16.6.3 Specializing Members but Not the Class . . . . 16.6.4 Class-Template Partial Specializations . . . . . 16.7 Overloading and Function Templates . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

623 624 625 627 628 630 632 633 636 637 642 643 647 651 655 655 658 660 664 665 666 667 668 671 672 675 677 678 679 683

xvi

Contents Defined Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683

Part V Advanced Topics Chapter 17 Tools for Large Programs 17.1 Exception Handling . . . . . . . . . . . . . . . . . . 17.1.1 Throwing an Exception of Class Type . . . 17.1.2 Stack Unwinding . . . . . . . . . . . . . . . 17.1.3 Catching an Exception . . . . . . . . . . . . 17.1.4 Rethrow . . . . . . . . . . . . . . . . . . . . 17.1.5 The Catch-All Handler . . . . . . . . . . . . 17.1.6 Function Try Blocks and Constructors . . . 17.1.7 Exception Class Hierarchies . . . . . . . . . 17.1.8 Automatic Resource Deallocation . . . . . 17.1.9 The auto_ptr Class . . . . . . . . . . . . . 17.1.10 Exception Specifications . . . . . . . . . . . 17.1.11 Function Pointer Exception Specifications . 17.2 Namespaces . . . . . . . . . . . . . . . . . . . . . . 17.2.1 Namespace Definitions . . . . . . . . . . . 17.2.2 Nested Namespaces . . . . . . . . . . . . . 17.2.3 Unnamed Namespaces . . . . . . . . . . . . 17.2.4 Using Namespace Members . . . . . . . . . 17.2.5 Classes, Namespaces, and Scope . . . . . . 17.2.6 Overloading and Namespaces . . . . . . . 17.2.7 Namespaces and Templates . . . . . . . . . 17.3 Multiple and Virtual Inheritance . . . . . . . . . . 17.3.1 Multiple Inheritance . . . . . . . . . . . . . 17.3.2 Conversions and Multiple Base Classes . . 17.3.3 Copy Control for Multiply Derived Classes 17.3.4 Class Scope under Multiple Inheritance . . 17.3.5 Virtual Inheritance . . . . . . . . . . . . . . 17.3.6 Virtual Base Class Declaration . . . . . . . 17.3.7 Special Initialization Semantics . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . . . . .

685 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

687 688 689 691 693 695 696 696 697 700 702 706 711 712 712 717 718 720 724 727 730 731 731 734 737 737 740 742 744 748 748

Chapter 18 Specialized Tools and Techniques 18.1 Optimizing Memory Allocation . . . . . . . . . . . . . . . . 18.1.1 Memory Allocation in C++ . . . . . . . . . . . . . . 18.1.2 The allocator Class . . . . . . . . . . . . . . . . . 18.1.3 operator new and operator delete Functions 18.1.4 Placement new Expressions . . . . . . . . . . . . . . 18.1.5 Explicit Destructor Invocation . . . . . . . . . . . . 18.1.6 Class Specific new and delete . . . . . . . . . . . . 18.1.7 A Memory-Allocator Base Class . . . . . . . . . . . 18.2 Run-Time Type Identification . . . . . . . . . . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

753 754 754 755 759 761 762 763 766 772

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Contents 18.2.1 The dynamic_cast Operator . . . . 18.2.2 The typeid Operator . . . . . . . . . 18.2.3 Using RTTI . . . . . . . . . . . . . . . 18.2.4 The type_info Class . . . . . . . . . 18.3 Pointer to Class Member . . . . . . . . . . . . 18.3.1 Declaring a Pointer to Member . . . . 18.3.2 Using a Pointer to Class Member . . . 18.4 Nested Classes . . . . . . . . . . . . . . . . . . 18.4.1 A Nested-Class Implementation . . . 18.4.2 Name Lookup in Nested Class Scope 18.5 Union: A Space-Saving Class . . . . . . . . . 18.6 Local Classes . . . . . . . . . . . . . . . . . . . 18.7 Inherently Nonportable Features . . . . . . . 18.7.1 Bit-fields . . . . . . . . . . . . . . . . . 18.7.2 volatile Qualifier . . . . . . . . . . 18.7.3 Linkage Directives: extern "C" . . . Chapter Summary . . . . . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . . . . .

17 . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

773 775 777 779 780 781 783 786 787 791 792 796 797 798 799 801 805 805

Appendix A The Library A.1 Library Names and Headers . . . . . . . . . . . . . . . A.2 A Brief Tour of the Algorithms . . . . . . . . . . . . . A.2.1 Algorithms to Find an Object . . . . . . . . . . A.2.2 Other Read-Only Algorithms . . . . . . . . . . A.2.3 Binary-Search Algorithms . . . . . . . . . . . . A.2.4 Algorithms that Write Container Elements . . A.2.5 Partitioning and Sorting Algorithms . . . . . . A.2.6 General Reordering Operations . . . . . . . . . A.2.7 Permutation Algorithms . . . . . . . . . . . . . A.2.8 Set Algorithms for Sorted Sequences . . . . . . A.2.9 Minimum and Maximum Values . . . . . . . . A.2.10 Numeric Algorithms . . . . . . . . . . . . . . . A.3 The IO Library Revisited . . . . . . . . . . . . . . . . . A.3.1 Format State . . . . . . . . . . . . . . . . . . . . A.3.2 Many Manipulators Change the Format State . A.3.3 Controlling Output Formats . . . . . . . . . . . A.3.4 Controlling Input Formatting . . . . . . . . . . A.3.5 Unformatted Input/Output Operations . . . . A.3.6 Single-Byte Operations . . . . . . . . . . . . . . A.3.7 Multi-Byte Operations . . . . . . . . . . . . . . A.3.8 Random Access to a Stream . . . . . . . . . . . A.3.9 Reading and Writing to the Same File . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

809 810 811 811 813 814 815 817 818 820 821 822 823 825 825 825 826 833 834 834 835 837 840

Index

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

843

This page intentionally left blank

Preface C++ Primer, Fourth Edition, provides a comprehensive introduction to the C++ language. As a primer, it provides a clear tutorial approach to the language, enhanced by numerous examples and other learning aids. Unlike most primers, it also provides a detailed description of the language, with particular emphasis on current and effective programming techniques. Countless programmers have used previous editions of C++ Primer to learn C++. In that time C++ has matured greatly. Over the years, the focus of the language—and of C++ programmers—has grown beyond a concentration on runtime efficiency to focus on ways of making programmers more efficient. With the widespread availability of the standard library, it is possible to use and learn C++ more effectively than in the past. This revision of the C++ Primer reflects these new possiblities.

Changes to the Fourth Edition In this edition, we have completely reorganized and rewritten the C++ Primer to highlight modern styles of C++ programming. This edition gives center stage to using the standard library while deemphasizing techniques for low-level programming. We introduce the standard library much earlier in the text and have reformulated the examples to take advantage of library facilities. We have also streamlined and reordered the presentation of language topics. In addition to restructuring the text, we have incorporated several new elements to enhance the reader’s understanding. Each chapter concludes with a Chapter Summary and glossary of Defined Terms, which recap the chapter’s most important points. Readers should use these sections as a personal checklist: If you do not understand a term, restudy the corresponding part of the chapter. We’ve also incorporated a number of other learning aids in the body of the text: • Important terms are indicated in bold; important terms that we assume are already familiar to the reader are indicated in bold italics. Each term appears in the chapter’s Defined Terms section. • Throughout the book, we highlight parts of the text to call attention to important aspects of the language, warn about common pitfalls, suggest good programming practices, and provide general usage tips. We hope that these notes will help readers more quickly digest important concepts and avoid common pitfalls. xix

xx

Preface • To make it easier to follow the relationships among features and concepts, we provide extensive forward and backward cross-references. • We have provided sidebar discussions that focus on important concepts and supply additional explanations for topics that programmers new to C++ often find most difficult. • Learning any programming language requires writing programs. To that end, the primer provides extensive examples throughout the text. Source code for the extended examples is available on the Web at the following URL: http://www.awprofessional.com/cpp_primer

What hasn’t changed from earlier versions is that the book remains a comprehensive tutorial introduction to C++. Our intent is to provide a clear, complete and correct guide to the language. We teach the language by presenting a series of examples, which, in addition to explaining language features, show how to make the best use of C++. Although knowledge of C (the language on which C++ was originally based) is not assumed, we do assume the reader has programmed in a modern block-structured language.

Structure of This Book C++ Primer provides an introduction to the International Standard on C++, covering both the language proper and the extensive library that is part of that standard. Much of the power of C++ comes from its support for programming with abstractions. Learning to program effectively in C++ requires more than learning new syntax and semantics. Our focus is on how to use the features of C++ to write programs that are safe, that can be built quickly, and yet offer performance comparable to the sorts of low-level programs often written in C. C++ is a large language and can be daunting to new users. Modern C++ can be thought of as comprising three parts: • The low-level language, largely inherited from C • More advanced language features that allow us to define our own data types and to organize large-scale programs and systems • The standard library, which uses these advanced features to provide a set of useful data structures and algorithms Most texts present C++ in this same order: They start by covering the low-level details and then introduce the the more advanced language features. They explain the standard library only after having covered the entire language. The result, all too often, is that readers get bogged down in issues of low-level programming or the complexities of writing type definitions and never really understand the power of programming in a more abstract way. Needless to say, readers also often do not learn enough to build their own abstractions. In this edition we take a completely different tack. We start by covering the basics of the language and the library together. Doing so allows you, the reader, to

Preface write significant programs. Only after a thorough grounding in using the library— and writing the kinds of abstract programs that the libary allows—do we move on to those features of C++ that will enable you to write your own abstractions. Parts I and II cover the basic language and library facilities. The focus of these parts is to learn how to write C++ programs and how to use the abstractions from the library. Most C++ programmers need to know essentially everything covered in this portion of the book. In addition to teaching the basics of C++, the material in Parts I and II serves another important purpose. The library facilities are themselves abstract data types written in C++. The library can be defined using the same class-construction features that are available to any C++ programmer. Our experience in teaching C++ is that by first using well-designed abstract types, readers find it easier to understand how to build their own types. Parts III through V focus on how we can write our own types. Part III introduces the heart of C++: its support for classes. The class mechanism provides the basis for writing our own abstractions. Classes are also the foundation for object-oriented and generic programming, which we cover in Part IV. The Primer concludes with Part V, which covers advanced features that are of most use in structuring large, complex systems.

Acknowledgments As in previous editions of this Primer, we’d like to extend our thanks to Bjarne Stroustrup for his tireless work on C++ and for his friendship to these authors throughout most of that time. We’d also like to thank Alex Stepanov for his original insights that led to the containers and algorithms that form the core of the standard library. Finally, our thanks go to the C++ Standards committee members for their hard work in clarifying, refining, and improving C++ over many years. We also extend our deep-felt thanks to our reviewers, whose helpful comments on multiple drafts led us to make improvements great and small throughout the book: Paul Abrahams, Michael Ball, Mary Dageforde, Paul DuBois, Matt Greenwood, Matthew P. Johnson, Andrew Koenig, Nevin Liber, Bill Locke, Robert Murray, Phil Romanik, Justin Shaw, Victor Shtern, Clovis Tondo, Daveed Vandevoorde, and Steve Vinoski. This book was typeset using LATEX and the many packages that accompany the A L TEX distribution. Our well-justified thanks go to the members of the LATEX community, who have made available such powerful typesetting tools. The examples in this book have been compiled on the GNU and Microsoft compilers. Our thanks to their developers, and to those who have developed all the other C++ compilers, thereby making C++ a reality. Finally, we thank the fine folks at Addison-Wesley who have shepherded this edition through the publishing process: Debbie Lafferty, our original editor, who initiated this edition and who had been with the Primer from its very first edition; Peter Gordon, our new editor, whose insistence on updating and streamlining the text have, we hope, greatly improved the presentation; Kim Boedigheimer, who keeps us all on schedule; and Tyrrell Albaugh, Jim Markham, Elizabeth Ryan, and John Fuller, who saw us through the design and production process.

xxi

This page intentionally left blank

C

H

A

P

T

E

R

1

G ETTING STARTED

C ONTENTS Section 1.1 Writing a Simple C++ Program Section 1.2 A First Look at Input/Output . Section 1.3 A Word About Comments . . . Section 1.4 Control Structures . . . . . . . Section 1.5 Introducing Classes . . . . . . Section 1.6 The C++ Program . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . Defined Terms . . . . . . . . . . . . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

2 5 10 11 20 25 28 28

This chapter introduces most of the basic elements of C++: built-in, library, and class types; variables; expressions; statements; and functions. Along the way, we’ll briefly explain how to compile and execute a program. Having read this chapter and worked through the exercises, the reader should be able to write, compile, and execute simple programs. Subsequent chapters will explain in more detail the topics introduced here.

1

2

Getting Started

Learning a new

programming language requires writing programs. In this chapter, we’ll write a program to solve a simple problem that represents a common data-processing task: A bookstore keeps a file of transactions, each of which records the sale of a given book. Each transaction contains an ISBN (International Standard Book Number, a unique identifier assigned to most books published throughout the world), the number of copies sold, and the price at which each copy was sold. Each transaction looks like 0-201-70353-X 4 24.99

where the first element is the ISBN, the second is the number of books sold, and the last is the sales price. Periodically the bookstore owner reads this file and computes the number of copies of each title sold, the total revenue from that book, and the average sales price. We want to supply a program do these computations. Before we can write this program we need to know some basic features of C++. At a minimum we’ll need to know how to write, compile, and execute a simple program. What must this program do? Although we have not yet designed our solution, we know that the program must • Define variables • Do input and output • Define a data structure to hold the data we’re managing • Test whether two records have the same ISBN • Write a loop that will process every record in the transaction file We’ll start by reviewing these parts of C++ and then write a solution to our bookstore problem.

1.1

Writing a Simple C++ Program

Every C++ program contains one or more functions, one of which must be named main. A function consists of a sequence of statements that perform the work of the function. The operating system executes a program by calling the function named main. That function executes its constituent statements and returns a value to the operating system. Here is a simple version of main does nothing but return a value: int main() { return 0; }

The operating system uses the value returned by main to determine whether the program succeeded or failed. A return value of 0 indicates success. The main function is special in various ways, the most important of which are that the function must exist in every C++ program and it is the (only) function that the operating system explicitly calls.

Section 1.1 Writing a Simple C++ Program We define main the same way we define other functions. A function definition specifies four elements: the return type, the function name, a (possibly empty) parameter list enclosed in parentheses, and the function body. The main function may have only a restricted set of parameters. As defined here, the parameter list is empty; Section 7.2.6 (p. 243) will cover the other parameters that can be defined for main. The main function is required to have a return type of int, which is the type that represents integers. The int type is a built-in type, which means that the type is defined by the language. The final part of a function definition, the function body, is a block of statements starting with an open curly brace and ending with a close curly: { return 0; }

The only statement in our program is a return, which is a statement that terminates a function. Note the semicolon at the end of the return statement. Semicolons mark the end of most statements in C++. They are easy to overlook, but when forgotten can lead to mysterious compiler error messages. When the return includes a value such as 0, that value is the return value of the function. The value returned must have the same type as the return type of the function or be a type that can be converted to that type. In the case of main the return type must be int, and the value 0 is an int. On most systems, the return value from main is a status indicator. A return value of 0 indicates the successful completion of main. Any other return value has a meaning that is defined by the operating system. Usually a nonzero return indicates that an error occurred. Each operating system has its own way of telling the user what main returned.

1.1.1

Compiling and Executing Our Program

Having written the program, we need to compile it. How you compile a program depends on your operating system and compiler. For details on how your particular compiler works, you’ll need to check the reference manual or ask a knowledgeable colleague. Many PC-based compilers are run from an integrated development environment (IDE) that bundles the compiler with associated build and analysis tools. These environments can be a great asset in developing complex programs but require a fair bit of time to learn how to use effectively. Most of these environments include a point-and-click interface that allows the programmer to write a program and use various menus to compile and execute the program. Learning how to use such environments is well beyond the scope of this book. Most compilers, including those that come with an IDE, provide a commandline interface. Unless you are already familiar with using your compiler’s IDE,

3

4

Getting Started it can be easier to start by using the simpler, command-line interface. Using the command-line interface lets you avoid the overhead of learning the IDE before learning the language.

Program Source File Naming Convention Whether we are using a command-line interface or an IDE, most compilers expect that the program we want to compile will be stored in a file. Program files are referred to as source files. On most systems, a source file has a name that consists of two parts: a file name—for example, prog1—and a file suffix. By convention, the suffix indicates that the file is a program. The suffix often also indicates what language the program is written in and selects which compiler to run. The system that we used to compile the examples in this book treats a file with a suffix of .cc as a C++ program and so we stored this program as prog1.cc

The suffix for C++ program files depends on which compiler you’re running. Other conventions include prog1.cxx prog1.cpp prog1.cp prog1.C

I NVOKING THE GNU OR M ICROSOFT C OMPILERS The command used to invoke the C++ compiler varies across compilers and operating systems. The most common compilers are the GNU compiler and the Microsoft Visual Studio compilers. By default the command to invoke the GNU compiler is g++: $ g++ prog1.cc -o prog1 where $ is the system prompt. This command generates an executable file named prog1 or prog1.exe, depending on the operating system. On UNIX, executable files have no suffix; on Windows, the suffix is .exe. The -o prog1 is an argument to the compiler and names the file in which to put the executable file. If the -o prog1 is omitted, then the compiler generates an executable named a.out on UNIX systems and a.exe on Windows. The Microsoft compilers are invoked using the command cl: C:\directory> cl -GX prog1.cpp where C:directory> is the system prompt and directory is the name of the current directory. The command to invoke the compiler is cl, and -GX is an option that is required for programs compiled using the command-line interface. The Microsoft compiler automatically generates an executable with a name that corresponds to the source file name. The executable has the suffix .exe and the same name as the source file name. In this case, the executable is named prog1.exe. For further information consult your compiler’s user’s guide.

Section 1.2 A First Look at Input/Output

Running the Compiler from the Command Line If we are using a command-line interface, we will typically compile a program in a console window (such as a shell window on a UNIX system or a Command Prompt window on Windows). Assuming that our main program is in a file named prog1.cc, we might compile it by using a command such as: $ CC prog1.cc

where CC names the compiler and $ represents the system prompt. The output of the compiler is an executable file that we invoke by naming it. On our system, the compiler generates the executable in a file named a.exe. UNIX compilers tend to put their executables in a file named a.out. To run an executable we supply that name at the command-line prompt: $ a.exe

executes the program we compiled. On UNIX systems you sometimes must also specify which directory the file is in, even if it is in the current directory. In such cases, we would write $ ./a.exe

The “.” followed by a slash indicates that the file is in the current directory. The value returned from main is accessed in a system-dependent manner. On both UNIX and Windows systems, after executing the program, you must issue an appropriate echo command. On UNIX systems, we obtain the status by writing $ echo $?

To see the status on a Windows system, we write C:\directory> echo %ERRORLEVEL%

E X E R C I S E S S E C T I O N 1.1.1 Exercise 1.1: Review the documentation for your compiler and determine what file naming convention it uses. Compile and run the main program from page 2. Exercise 1.2: Change the program to return -1. A return value of -1 is often treated as an indicator that the program failed. However, systems vary as to how (or even whether) they report a failure from main. Recompile and rerun your program to see how your system treats a failure indicator from main.

1.2

A First Look at Input/Output

C++ does not directly define any statements to do input or output (IO). Instead, IO is provided by the standard library. The IO library provides an extensive set of

5

6

Getting Started facilities. However, for many purposes, including the examples in this book, one needs to know only a few basic concepts and operations. Most of the examples in this book use the iostream library, which handles formatted input and output. Fundamental to the iostream library are two types named istream and ostream, which represent input and output streams, respectively. A stream is a sequence of characters intended to be read from or written to an IO device of some kind. The term “stream” is intended to suggest that the characters are generated, or consumed, sequentially over time.

1.2.1

Standard Input and Output Objects

The library defines four IO objects. To handle input, we use an object of type istream named cin (pronounced “see-in”). This object is also referred to as the standard input. For output, we use an ostream object named cout (pronounced “see-out”). It is often referred to as the standard output. The library also defines two other ostream objects, named cerr and clog (pronounced “see-err” and “see-log,” respectively). The cerr object, referred to as the standard error, is typically used to generate warning and error messages to users of our programs. The clog object is used for general information about the execution of the program. Ordinarily, the system associates each of these objects with the window in which the program is executed. So, when we read from cin, data is read from the window in which the program is executing, and when we write to cout, cerr, or clog, the output is written to the same window. Most operating systems give us a way of redirecting the input or output streams when we run a program. Using redirection we can associate these streams with files of our choosing.

1.2.2

A Program that Uses the IO Library

So far, we have seen how to compile and execute a simple program, although that program did no work. In our overall problem, we’ll have several records that refer to the same ISBN. We’ll need to consolidate those records into a single total, implying that we’ll need to know how to add the quantities of books sold. To see how to solve part of that problem, let’s start by looking at how we might add two numbers. Using the IO library, we can extend our main program to ask the user to give us two numbers and then print their sum: #include int main() { std::cout v1 >> v2; std::cout