Absolute C++

  • 81 300 9
  • 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

This page intentionally left blank

www.itpub.net

ABSOLUTE 5th edition C++

This page intentionally left blank

www.itpub.net

ABSOLUTE C++ 5th Edition

Walter Savitch University of California, San Diego

Contributor

Kenrick Mock University of Alaska Anchorage

Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montréal Toronto Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

Vice President and Editorial Director, ECS: Marcia Horton Executive Editor: Matt Goldstein Editorial Assistants: Chelsea Kharakozova/ Emma Snider Vice President Marketing: Patrice Jones Marketing Manager: Yez Alayan Marketing Coordinator: Kathryn Ferranti Vice President and Director of Production: Vince O’Brien Managing Editor: Jeff Holcomb Senior Production Project Manager: Marilyn Lloyd Manufacturing Manager: Nick Skilitis

Operations Specialist: Lisa McDowell Text Designer: Joyce Cosentino Wells Cover Designer: Anthony Gemmellaro Cover Image: © Shutterstock Media Editor: Dan Sandin Manager, Rights and Permissions: Michael Joyce Text Permissions—assessment: Dana Weightman Text Permissions—clearance: Nicole Coffineau/ Creative Compliance Full-Service Vendor: GEX Publishing Services Project Management: GEX Publishing Services Printer/Binder: Edwards Brothers Cover Printer: Lehigh-Phoenix Color

This book was composed in InDesign. Basal font is Adobe Garamond 10/12. Display font is Optima LT Std. Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the appropriate page within text. Copyright © 2013, 2010, 2008, 2006, 2004 by Pearson Education, Inc., publishing as Addison-Wesley. All rights reserved. Manufactured in the United States of America. This publication is protected by Copyright, and permission should 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. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290. Many of the designations 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 in initial caps or all caps.

Library of Congress Cataloging-in-Publication Data Savitch, Walter J. Absolute C++ / Walter Savitch ; contributor, Kenrick Mock. -- 5th ed. p. cm. Includes bibliographical references and index. ISBN 978-0-13-283071-3 (alk. paper) 1. C++ (Computer program language) I. Mock, Kenrick. II. Title. QA76.73.C153S279 2010 005.13’3--dc23 2012001325

1 2 3 4 5 6 7 8 9 10—EB—15 14 13 12 ISBN-10: 0-13-283071-X ISBN-13: 978-0-13-283071-3

www.itpub.net

Preface

This book is designed to be a textbook and reference for programming in the C++ language. Although it does include programming techniques, it is organized around the features of the C++ language, rather than any particular curriculum of techniques. The main audience I had in mind is undergraduate students who had not had extensive programming experience with the C++ language. As such, this book is a suitable C++ text or reference for a wide range of users. The introductory chapters are written at a level that is accessible to beginners, while the boxed sections of those chapters serve to introduce more experienced programmers to basic C++ syntax. Later chapters are also understandable to beginners, but are written at a level suitable for students who have progressed to these more advanced topics. Absolute C++ is also suitable for anyone learning the C++ language on their own. (For those who want a textbook with more pedagogical material and more on very basic programming technique, try my text Problem Solving with C++, Eighth Edition, Pearson Education.) The C++ coverage in this book goes well beyond what a beginner needs to know. In particular, it has extensive coverage of inheritance, polymorphism, exception handling, and the Standard Template Library (STL), as well as basic coverage of patterns and the unified modeling language (UML).

CHANGES IN THIS EDITION This fifth edition presents the same programming philosophy as the fourth edition. For instructors, you can teach the same course, presenting the same topics in the same order with no changes in the material covered or the chapters assigned. Changes include: ■



■ ■

■ ■

Chapter 1 now includes a short introduction to the string class and Chapter 2 includes a short introduction to reading data from a text file. Together, this material allows instructors to present students with problems of larger scale and real-world applicability as early as Chapter 2. Chapter 12 now includes a section on using stringstream to convert between strings and other data types. Chapter 13 briefly describes tail recursion and gives an example of mutual recursion. Ten new self-test exercises have been added along with twenty-five new Programming Projects. By request, some of these are longer and less prescriptive projects that give the student more practice designing programming solutions. Several errors that were found in the fourth edition have been corrected. Fifteen new VideoNotes have been added to the book’s website (www.pearsonhighered. com/savitch) for a total of forty-six videos. These VideoNotes walk students through the process of problem solving and coding to reinforce key programming concepts. An icon appears in the margin of the book when a video is available regarding the corresponding topic in the text.

ANSI/ISO C++ STANDARD This edition is fully compatible with compilers that meet the latest ANSI/ISO C++ standard.

v

vi

Preface

STANDARD TEMPLATE LIBRARY The Standard Template Library (STL) is an extensive collection of preprogrammed data structure classes and algorithms. The STL is perhaps as big a topic as the core C++ language, so I have included a substantial introduction to STL. There is a full chapter on the general topic of templates and a full chapter on the particulars of STL, as well as other material on, or related to, STL at other points in the text.

OBJECT-ORIENTED PROGRAMMING This book is organized around the structure of C++. As such, the early chapters cover aspects of C++ that are common to most high-level programming languages but are not particularly oriented toward object-oriented programming (OOP). For a reference book—and for a book for learning a second language—this makes sense. However, I consider C++ to be an OOP language. If you are programming in C++ and not C, you must be using the OOP features of C++. This text offers extensive coverage of encapsulation, inheritance, and polymorphism as realized in the C++ language. Chapter 20, on patterns and UML, gives additional coverage of OOP-related material.

FLEXIBILITY IN TOPIC ORDERING This book allows instructors wide latitude in reordering the material. This is important if a book is to serve as a reference. This is also in keeping with my philosophy of accommodating the instructor’s style, rather than tying the instructor to my own personal preference of topic ordering. Each chapter introduction explains what material must already have been covered before each section of the chapter can be covered.

ACCESSIBLE TO STUDENTS It is not enough for a book to present the right topics in the right order. It is not even enough for it be correct and clear to an instructor. The material also needs to be presented in a way that is accessible to the novice. Like my other textbooks, which proved to be very popular with students, this book was written to be friendly and accessible to the student.

SUMMARY BOXES Each major point is summarized in a boxed section. These boxed sections are spread throughout each chapter. They serve as summaries of the material, as a quick reference source, and as a quick way to learn the C++ syntax for a feature you know about in general but for which you do not know the C++ particulars.

SELF-TEST EXERCISES Each chapter contains numerous self-test exercises. Complete answers for all the selftest exercises are given at the end of each chapter.

www.itpub.net

Preface

VIDEO NOTES VideoNote

VideoNotes are step-by-step videos that guide readers through the solution to an end of chapter problem or further illuminate a concept presented in the text. Icons in the text indicate where a VideoNote enhances a topic. Fully navigable problems allow for self-paced instruction. VideoNotes are located at www.pearsonhighered.com/savitch.

OTHER FEATURES Pitfall sections, programming technique sections, and examples of complete programs with sample input and output are given throughout each chapter. Each chapter ends with a summary and a collection of programming projects.

ONLINE PRACTICE AND ASSESSMENT WITH MyProgrammingLab MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages. A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice problems organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong—and why. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review. MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the makers of the CodeLab interactive programming exercise system. For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com.

SUPPORT MATERIAL The following support materials are available to all users of this book at www.pearsonhighered.com/cssupport: ■

Source code from the book

The following resources are available to qualified instructors only at www. pearsonhighered.com/irc. Please contact your local sales representative for access information. ■ ■

Instructor’s Manual with Solutions PowerPoint® slides

vii

viii

Preface

ACKNOWLEDGMENTS Numerous individuals have contributed invaluable help and support to making this book happen. Frank Ruggirello and Susan Hartman at Addison-Wesley first conceived the idea and supported the first edition, for which I owe them a debt of gratitude. A special thanks to Matt Goldstein who was the editor for the second, third, and fourth editions. His help and support were critical to making this project succeed. Chelsea Kharakozova, Marilyn Lloyd, Yez Alayan, and the other fine people at Pearson Education also provided valuable support and encouragement. The following reviewers provided suggestions for the book. I thank them all for their hard work and helpful comments. Richard Albright J. Boyd Trolinger Jerry K. Bilbrey, Jr Albert M. K. Cheng David Cherba Fredrick H. Colclough Drue Coles Stephen Corbesero Christopher E. Cramer Ron DiNapoli Qin Ding Martin Dulberg H. E. Dunsmore Evan Golub Terry Harvey Joanna Klukowska Lawrence S. Kroll Stephen P. Leach Alvin S. Lim Tim H. Lin R. M. Lowe Jeffrey L. Popyack Amar Raheja Victoria Rayskin Loren Rhodes Jeff Ringenberg

University of Delaware Butte College Francis Marion University University of Houston Michigan State University Colorado Technical University Boston University Moravian College Cornell University Pennsylvania State University, Harrisburg North Carolina State University Purdue University University of Maryland University of Delaware Hunter College, CUNY San Francisco State University Florida State University Auburn University Cal Poly Pomona Clemson University Drexel University Cal Poly Pomona University of Central Los Angeles Juniata College University of Michigan

www.itpub.net

Preface

Victor Shtern Aaron Striegel J. Boyd Trolinger Chrysafis Vogiatzis Joel Weinstein Dick Whalen

Boston University University of Notre Dame Butte College University of Florida Northeastern University College of Southern Maryland

A special thanks goes to Kenrick Mock (University of Alaska Anchorage) who executed the updating of this edition. He once again had the difficult job of satisfying me, the editor, and himself. I thank him for a truly excellent job. Walter Savitch

ix

LOCATION OF VIDEONOTES IN THE TEXT

VideoNote

www.pearsonhighered.com/savitch

Chapter 1

Compiling and Running a C++ Program, page 4 Solution to Programming Project 1.11, page 44

Chapter 2

Nested Loop Example, page 83 Solution to Programming Project 2.5, page 95 Solution to Programming Project 2.9, page 96 Solution to Programming Project 2.10, page 96

Chapter 3

Generating Random Numbers, page 107 Scope Walkthrough, page 125 Solution to Programming Project 3.9, page 140

Chapter 4

Using an Integrated Debugger, page 173 Solution to Programming Project 4.4, page 180 Solution to Programming Project 4.11, page 181

Chapter 5

Array Walkthrough, page 187 Solution to Programming Project 5.7, page 233 Solution to Programming Project 5.15, page 237

Chapter 6

Solution to Programming Project 6.5, page 272 Solution to Programming Project 6.9, page 273

Chapter 7

Constructor Walkthrough, page 276 Solution to Programming Project 7.4, page 316 Solution to Programming Project 7.7, page 317

Chapter 8

Solution to Programming Project 8.7, page 366

Chapter 9

Using cin and getline with the string class, page 399 Solution to Programming Project 9.11, page 417 Solution to Programming Project 9.13, page 418

Chapter 10

Example of Shallow Copy vs. Deep Copy, page 459 Solution to Programming Project 10.5, page 469

Chapter 11

Avoiding Multiple Definitions with #ifndef, page 484 Solution to Programming Project 11.5, page 512

Chapter 12

Walkthrough of the stringstream demo, page 554 Solution to Programming Project 12.17, page 566 Solution to Programming Project 12.25, page 570

Chapter 13

Recursion and the Stack, page 582 Walkthrough of Mutual Recursion, page 591 Solution to Programming Project 13.9, page 609 Solution to Programming Project 13.11, page 610

Chapter 14

Solution to Programming Project 14.7, page 657

www.itpub.net

Chapter 15

Solution to Programming Project 15.5, page 689 Solution to Programming Project 15.7, page 690

Chapter 16

Solution to Programming Project 16.3, page 728 Solution to Programming Project 16.7, page 729

Chapter 17

Solution to Programming Project 17.5, page 820 Solution to Programming Project 17.11, page 822

Chapter 18

Solution to Programming Project 18.5, page 854

Chapter 19

Solution to Programming Project 19.9, page 909 Solution to Programming Project 19.12, page 911

Chapter 20

Solution to Programming Project 20.6, page 931

This page intentionally left blank

www.itpub.net

Brief Contents

Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8

C++ BASICS 1 FLOW OF CONTROL 45 FUNCTION BASICS

PARAMETERS AND OVERLOADING 145 ARRAYS

185

STRUCTURES AND CLASSES

239

CONSTRUCTORS AND OTHER TOOLS

275

OPERATOR OVERLOADING, FRIENDS, AND REFERENCES

Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20

99

321

STRINGS 367 POINTERS AND DYNAMIC ARRAYS 419 SEPARATE COMPILATION AND NAMESPACES

471

STREAMS AND FILE I/O 515 RECURSION INHERITANCE

571 613

POLYMORPHISM AND VIRTUAL FUNCTIONS 661 TEMPLATES 693 LINKED DATA STRUCTURES

731

EXCEPTION HANDLING 825 STANDARD TEMPLATE LIBRARY 857 PATTERNS AND UML

(online at www.pearsonhighered.com/

savitch)

Appendix 1 Appendix 2 Appendix 3 Appendix 4 Appendix 5

C++ KEYWORDS 915 PRECEDENCE OF OPERATORS

917

THE ASCII CHARACTER SET 919 SOME LIBRARY FUNCTIONS 921 OLD AND NEW HEADER FILES INDEX

929

931

xiii

This page intentionally left blank

www.itpub.net

Contents

Chapter 1 1.1

C++ Basics 1 INTRODUCTION TO C++ 2 Origins of the C++ Language 2 C++ and Object-Oriented Programming The Character of C++ 3 C++ Terminology 4 A Sample C++ Program 4

1.2

3

VARIABLES, EXPRESSIONS, AND ASSIGNMENT STATEMENTS 6 Identifiers 7 Variables 8 Assignment Statements 10 Introduction to the string class 12 PITFALL: Uninitialized Variables 12 TIP: Use Meaningful Names 13 More Assignment Statements 14 Assignment Compatibility 15 Literals 16 Escape Sequences 17 Naming Constants 17 Arithmetic Operators and Expressions 19 Integer and Floating-Point Division 21 PITFALL: Division with Whole Numbers 22 Type Casting 23 Increment and Decrement Operators 25 PITFALL: Order of Evaluation 27

1.3

CONSOLE INPUT/OUTPUT 28 Output Using cout 28 New Lines in Output 29 TIP: End Each Program with \n or endl 30 Formatting for Numbers with a Decimal Point Output with cerr 32 Input Using cin 32 TIP: Line Breaks in I/O 35

30

xv

xvi

Contents

1.4

PROGRAM STYLE 36 Comments

1.5

36

LIBRARIES AND NAMESPACES

37

Libraries and include Directives 37 Namespaces 37 PITFALL: Problems with Library Names Chapter Summary 39 Answers to Self-Test Exercises Programming Projects 42

Chapter 2 2.1

Flow of Control

38

40

45

BOOLEAN EXPRESSIONS 45 Building Boolean Expressions 46 PITFALL: Strings of Inequalities 47 Evaluating Boolean Expressions 48 Precedence Rules 50 PITFALL: Integer Values Can Be Used as Boolean Values

2.2

54

BRANCHING MECHANISMS 56 if-else Statements

56 Compound Statements 58 PITFALL: Using = in Place of == 59 Omitting the else 61 Nested Statements 61 Multiway if-else Statement 61 The switch Statement 62 PITFALL: Forgetting a break in a switch Statement 65 TIP: Use switch Statements for Menus 65 Enumeration Types 66 The Conditional Operator 66

2.3

LOOPS 67 The while and do-while Statements 68 Increment and Decrement Operators Revisited 71 The Comma Operator 72 The for Statement 74 TIP: Repeat-N-Times Loops 76 PITFALL: Extra Semicolon in a for Statement 77 PITFALL: Infinite Loops 77 The break and continue Statements 80 Nested Loops 83

www.itpub.net

Contents

2.4

INTRODUCTION TO FILE INPUT 83 Reading From a Text File Using ifstream 84 Chapter Summary 87 Answers to Self-Test Exercises Programming Projects 93

Chapter 3 3.1

87

Function Basics 99 PREDEFINED FUNCTIONS

100

Predefined Functions That Return a Value Predefined void Functions 105 A Random Number Generator 107

3.2

100

PROGRAMMER-DEFINED FUNCTIONS 111 Defining Functions That Return a Value 112 Alternate Form for Function Declarations 114 PITFALL: Arguments in the Wrong Order 115 PITFALL: Use of the Terms Parameter and Argument 115 Functions Calling Functions 115 EXAMPLE: A Rounding Function 115 Functions That Return a Boolean Value 118 Defining void Functions 119 return Statements in void Functions 121 Preconditions and Postconditions 121 main Is a Function 123 Recursive Functions 123

3.3

SCOPE RULES

125

Local Variables 125 Procedural Abstraction 127 Global Constants and Global Variables 128 Blocks 131 Nested Scopes 132 TIP: Use Function Calls in Branching and Loop Statements Variables Declared in a for Loop 133 Chapter Summary 134 Answers to Self-Test Exercises Programming Projects 138

134

132

xvii

xviii

Contents

Chapter 4 4.1

Parameters and Overloading 145 PARAMETERS 146 Call-by-Value Parameters 146 A First Look at Call-by-Reference Parameters 148 Call-by-Reference Mechanism in Detail 151 Constant Reference Parameters 153 EXAMPLE: The swapValues Function 153 TIP: Think of Actions, Not Code 154 Mixed Parameter Lists 155 TIP: What Kind of Parameter to Use 156 PITFALL: Inadvertent Local Variables 158 TIP: Choosing Formal Parameter Names 159 EXAMPLE: Buying Pizza 160

4.2

OVERLOADING AND DEFAULT ARGUMENTS

163

Introduction to Overloading 163 PITFALL: Automatic Type Conversion and Overloading Rules for Resolving Overloading 167 EXAMPLE: Revised Pizza-Buying Program 169 Default Arguments 171

4.3

166

TESTING AND DEBUGGING FUNCTIONS 173 The assert Macro 173 Stubs and Drivers 174 Chapter Summary 177 Answers to Self-Test Exercises Programming Projects 179

Chapter 5 5.1

Arrays

177

185

INTRODUCTION TO ARRAYS 186 Declaring and Referencing Arrays 186 TIP: Use for Loops with Arrays 189 PITFALL: Array Indexes Always Start with Zero 189 TIP: Use a Defined Constant for the Size of an Array Arrays in Memory 190 PITFALL: Array Index out of Range 192 Initializing Arrays 192

5.2

189

ARRAYS IN FUNCTIONS 195 Indexed Variables as Function Arguments 195 Entire Arrays as Function Arguments 196

www.itpub.net

Contents The const Parameter Modifier 200 PITFALL: Inconsistent Use of const Parameters Functions That Return an Array 202 EXAMPLE: Production Graph 202

5.3

PROGRAMMING WITH ARRAYS 207 Partially Filled Arrays 207 TIP: Do Not Skimp on Formal Parameters EXAMPLE: Searching an Array 211 EXAMPLE: Sorting an Array 213

5.4

208

MULTIDIMENSIONAL ARRAYS 218 Multidimensional Array Basics 218 Multidimensional Array Parameters 219 EXAMPLE: Two-Dimensional Grading Program Chapter Summary 225 Answers to Self-Test Exercises Programming Projects 230

Chapter 6 6.1

201

220

226

Structures and Classes 239 STRUCTURES

240

Structure Types 242 PITFALL: Forgetting a Semicolon in a Structure Definition Structures as Function Arguments 246 TIP: Use Hierarchical Structures 247 Initializing Structures 249

6.1

CLASSES

252

Defining Classes and Member Functions 252 Encapsulation 258 Public and Private Members 259 Accessor and Mutator Functions 262 TIP: Separate Interface and Implementation 264 TIP: A Test for Encapsulation 265 Structures versus Classes 266 TIP: Thinking Objects 268 Chapter Summary 268 Answers to Self-Test Exercises Programming Projects 271

269

246

xix

xx

Contents

Chapter 7 7.1

Constructors and Other Tools 275 CONSTRUCTORS

276

Constructor Definitions 276 PITFALL: Constructors with No Arguments 281 Explicit Constructor Calls 282 TIP: Always Include a Default Constructor 283 EXAMPLE: BankAccount Class 285 Class Type Member Variables 292

7.2

MORE TOOLS

295

The const Parameter Modifier 295 PITFALL: Inconsistent Use of const 297 Inline Functions 301 Static Members 303 Nested and Local Class Definitions 306

7.3

VECTORS—A PREVIEW OF THE STANDARD TEMPLATE LIBRARY 307 Vector Basics 307 PITFALL: Using Square Brackets beyond the Vector Size TIP: Vector Assignment Is Well Behaved 311 Efficiency Issues 311 Chapter Summary 313 Answers to Self-Test Exercises Programming Projects 315

Chapter 8 8.1

309

313

Operator Overloading, Friends, and References 321 BASIC OPERATOR OVERLOADING 322 Overloading Basics 323 TIP: A Constructor Can Return an Object 328 Returning by const Value 329 Overloading Unary Operators 332 Overloading as Member Functions 332 TIP: A Class Has Access to All Its Objects 335 Overloading Function Application ( ) 335 PITFALL: Overloading &&, ||, and the Comma Operator 336

8.2

FRIEND FUNCTIONS AND AUTOMATIC TYPE CONVERSION 336 Constructors for Automatic Type Conversion 336 PITFALL: Member Operators and Automatic Type Conversion Friend Functions 338 Friend Classes 341 PITFALL: Compilers without Friends 342

337

www.itpub.net

Contents

8.3

REFERENCES AND MORE OVERLOADED OPERATORS 343 References 344 TIP: Returning Member Variables of a Class Type 345 Overloading >> and > variable; and getline 399 String Processing with the Class string 401 EXAMPLE: Palindrome Testing 404 Converting between string Objects and C-Strings 408 Chapter Summary 409 Answers to Self-Test Exercises Programming Projects 413

409

xxi

xxii

Contents

Chapter 10 10.1

Pointers and Dynamic Arrays 419 POINTERS 420 Pointer Variables 421 Basic Memory Management 429 PITFALL: Dangling Pointers 432 Dynamic Variables and Automatic Variables 432 TIP: Define Pointer Types 433 PITFALL: Pointers as Call-by-Value Parameters 435 Uses for Pointers 436

10.2

DYNAMIC ARRAYS

437

Array Variables and Pointer Variables 437 Creating and Using Dynamic Arrays 439 EXAMPLE: A Function That Returns an Array Pointer Arithmetic 444 Multidimensional Dynamic Arrays 445

10.3

442

CLASSES, POINTERS, AND DYNAMIC ARRAYS 448 The -> Operator 448 The this Pointer 449 Overloading the Assignment Operator 449 EXAMPLE: A Class for Partially Filled Arrays 456 Destructors 459 Copy Constructors 460 Chapter Summary 465 Answers to Self-Test Exercises Programming Projects 467

Chapter 11 11.1

465

Separate Compilation and Namespaces 471 SEPARATE COMPILATION 472 Encapsulation Reviewed 473 Header Files and Implementation Files EXAMPLE: DigitalTime Class 482 TIP: Reusable Components 483 Using #ifndef 483 TIP: Defining Other Libraries 485

11.2

NAMESPACES

473

487

Namespaces and using Directives Creating a Namespace 489 using Declarations 492

487

www.itpub.net

Contents Qualifying Names 493 TIP: Choosing a Name for a Namespace 495 EXAMPLE: A Class Definition in a Namespace 496 Unnamed Namespaces 497 PITFALL: Confusing the Global Namespace and the Unnamed Namespace 503 TIP: Unnamed Namespaces Replace the static Qualifier 504 TIP: Hiding Helping Functions 504 Nested Namespaces 505 TIP: What Namespace Specification Should You Use? 505 Chapter Summary 508 Answers to Self-Test Exercises Programming Projects 510

Chapter 12 12.1

Streams and File I/O I/O STREAMS

508

515

517

File I/O 517 PITFALL: Restrictions on Stream Variables 522 Appending to a File 522 TIP: Another Syntax for Opening a File 524 TIP: Check That a File Was Opened Successfully 526 Character I/O 528 Checking for the End of a File 529

12.2

TOOLS FOR STREAM I/O 533 File Names as Input 533 Formatting Output with Stream Functions 534 Manipulators 538 Saving Flag Settings 539 More Output Stream Member Functions 540 EXAMPLE: Cleaning Up a File Format 542 EXAMPLE: Editing a Text File 544

12.3

STREAM HIERARCHIES: A PREVIEW OF INHERITANCE 547 Inheritance among Stream Classes 547 EXAMPLE: Another newLine Function 549 Parsing Strings with the stringstream Class

12.4

RANDOM ACCESS TO FILES Chapter Summary 558 Answers to Self-Test Exercises Programming Projects 561

556 558

553

xxiii

xxiv

Contents

Chapter 13 13.1

Recursion 571 RECURSIVE void FUNCTIONS

573

EXAMPLE: Vertical Numbers 573 Tracing a Recursive Call 576 A Closer Look at Recursion 579 PITFALL: Infinite Recursion 580 Stacks for Recursion 582 PITFALL: Stack Overflow 583 Recursion versus Iteration 584

13.2

RECURSIVE FUNCTIONS THAT RETURN A VALUE 585 General Form for a Recursive Function That Returns a Value EXAMPLE: Another Powers Function 586 Mutual Recursion 591

13.3

585

THINKING RECURSIVELY 593 Recursive Design Techniques 593 Binary Search 594 Coding 596 Checking the Recursion 600 Efficiency 600 Chapter Summary 602 Answers to Self-Test Exercises Programming Projects 607

Chapter 14 14.1

603

Inheritance 613 INHERITANCE BASICS 614 Derived Classes 614 Constructors in Derived Classes 624 PITFALL: Use of Private Member Variables from the Base Class 626 PITFALL: Private Member Functions Are Effectively Not Inherited 628 The protected Qualifier 628 Redefinition of Member Functions 631 Redefining versus Overloading 632 Access to a Redefined Base Function 634 Functions That Are Not Inherited 635

14.2

PROGRAMMING WITH INHERITANCE 636 Assignment Operators and Copy Constructors in Derived Classes 636 Destructors in Derived Classes 637 EXAMPLE: Partially Filled Array with Backup 638 PITFALL: Same Object on Both Sides of the Assignment Operator 647

www.itpub.net

Contents EXAMPLE: Alternate Implementation of PFArrayDBak 647 TIP: A Class Has Access to Private Members of All Objects of the Class 650 TIP: “Is a” versus “Has a” 650 Protected and Private Inheritance 651 Multiple Inheritance 652 Chapter Summary 653 Answers to Self-Test Exercises Programming Projects 655

Chapter 15 15.1

653

Polymorphism and Virtual Functions 661 VIRTUAL FUNCTION BASICS 662 Late Binding 662 Virtual Function in C++ 663 TIP: The Virtual Property Is Inherited 669 TIP: When to Use a Virtual Function 670 PITFALL: Omitting the Definition of a Virtual Member Function Abstract Classes and Pure Virtual Functions 671 EXAMPLE: An Abstract Class 672

15.2

POINTERS AND VIRTUAL FUNCTIONS 674 Virtual Functions and Extended Type Compatibility PITFALL: The Slicing Problem 678 TIP: Make Destructors Virtual 679 Downcasting and Upcasting 680 How C++ Implements Virtual Functions 681 Chapter Summary 683 Answers to Self-Test Exercises Programming Projects 684

Chapter 16 16.1

674

684

Templates 693 FUNCTION TEMPLATES 694 Syntax for Function Templates 695 PITFALL: Compiler Complications 698 TIP: How to Define Templates 700 EXAMPLE: A Generic Sorting Function 701 PITFALL: Using a Template with an Inappropriate Type

16.2

CLASS TEMPLATES

707

Syntax for Class Templates 708 EXAMPLE: An Array Template Class 712 The vector and basic_string Templates

718

705

670

xxv

xxvi

Contents

16.3

TEMPLATES AND INHERITANCE

718

EXAMPLE: Template Class For a Partially Filled Array with Backup 719 Chapter Summary 724 Answers to Self-Test Exercises Programming Projects 728

Chapter 17 17.1

Linked Data Structures

724

731

NODES AND LINKED LISTS 733 Nodes 733 Linked Lists 738 Inserting a Node at the Head of a List 740 PITFALL: Losing Nodes 743 Inserting and Removing Nodes Inside a List 743 PITFALL: Using the Assignment Operator with Dynamic Data Structures 747 Searching a Linked List 747 Doubly Linked Lists 750 Adding a Node to a Doubly Linked List 752 Deleting a Node from a Doubly Linked List 752 EXAMPLE: A Generic Sorting Template Version of Linked List Tools 759

17.2

LINKED LIST APPLICATIONS

763

EXAMPLE: A Stack Template Class 763 EXAMPLE: A Queue Template Class 770 TIP: A Comment on Namespaces 773 Friend Classes and Similar Alternatives 774 EXAMPLE: Hash Tables With Chaining 777 Efficiency of Hash Tables 783 EXAMPLE: A Set Template Class 784 Efficiency of Sets Using Linked Lists 790

17.3

ITERATORS

791

Pointers as Iterators 792 Iterator Classes 792 EXAMPLE: An Iterator Class 794

17.4

TREES 800 Tree Properties 801 EXAMPLE: A Tree Template Class 803 Chapter Summary 808 Answers to Self-Test Exercises Programming Projects 818

809

www.itpub.net

Contents

Chapter 18 18.1

Exception Handling 825 EXCEPTION HANDLING BASICS 827 A Toy Example of Exception Handling 827 Defining Your Own Exception Classes 836 Multiple Throws and Catches 836 PITFALL: Catch the More Specific Exception First 840 TIP: Exception Classes Can Be Trivial 841 Throwing an Exception in a Function 841 Exception Specification 843 PITFALL: Exception Specification in Derived Classes 845

18.2

PROGRAMMING TECHNIQUES FOR EXCEPTION HANDLING 846 When to Throw an Exception 847 PITFALL: Uncaught Exceptions 848 PITFALL: Nested try-catch Blocks 849 PITFALL: Overuse of Exceptions 849 Exception Class Hierarchies 850 Testing for Available Memory 850 Rethrowing an Exception 851 Chapter Summary 851 Answers to Self-Test Exercises Programming Projects 853

Chapter 19 19.1

851

Standard Template Library 857 ITERATORS

859

Iterator Basics 859 PITFALL: Compiler Problems 864 Kinds of Iterators 865 Constant and Mutable Iterators 868 Reverse Iterators 870 Other Kinds of Iterators 871

19.2

CONTAINERS 872 Sequential Containers 872 PITFALL: Iterators and Removing Elements 877 TIP: Type Definitions in Containers 878 The Container Adapters stack and queue 878 PITFALL: Underlying Containers 879 The Associative Containers set and map 882 Efficiency 887

xxvii

xxviii

Contents

19.3

GENERIC ALGORITHMS 889 Running Times and Big-O Notation 890 Container Access Running Times 894 Nonmodifying Sequence Algorithms 895 Modifying Sequence Algorithms 899 Set Algorithms 900 Sorting Algorithms 902 Chapter Summary 902 Answers to Self-Test Exercises Programming Projects 905

903

Chapter 20

Patterns and UML (online at www.pearsonhighered.com/ savitch)

Appendix 1

C++ Keywords

Appendix 2

Precedence of Operators 917

Appendix 3

The ASCII Character Set 919

Appendix 4

Some Library Functions

Appendix 5

Old and New Header Files Index

915

921 929

931

www.itpub.net

C++ Basics

1.1 INTRODUCTION TO C++ 2 Origins of the C++ Language 2 C++ and Object-Oriented Programming 3 The Character of C++ 3 C++ Terminology 4 A Sample C++ Program 4 1.2 VARIABLES, EXPRESSIONS, AND ASSIGNMENT STATEMENTS 6 Identifiers 7 Variables 8 Assignment Statements 10 Introduction to the string class 12 Pitfall: Uninitialized Variables 12 Tip: Use Meaningful Names 13 More Assignment Statements 14 Assignment Compatibility 15 Literals 16 Escape Sequences 17 Naming Constants 17 Arithmetic Operators and Expressions 19 Integer and Floating-Point Division 21 Pitfall: Division with Whole Numbers 22 Type Casting 23 Increment and Decrement Operators 25 Pitfall: Order of Evaluation 27

Chapter Summary

39

1

1.3 CONSOLE INPUT/OUTPUT 28 Output Using cout 28 New Lines in Output 29 Tip: End Each Program with \n or endl 30 Formatting for Numbers with a Decimal Point 30 Output with cerr 32 Input Using cin 32 Tip: Line Breaks in I/O 35 1.4 PROGRAM STYLE 36 Comments 36 1.5 LIBRARIES AND NAMESPACES 37 Libraries and include Directives 37 Namespaces 37 Pitfall: Problems with Library Names 38

Answers to Self-Test Exercises

40

Programming Projects

42

1

C++ Basics

The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. It can follow analysis; but it has no power of anticipating any analytical relations or truths. Its province is to assist us in making available what we are already acquainted with. ADA AUGUSTA, Countess of Lovelace

Introduction This chapter introduces the C++ language and gives enough detail to allow you to handle simple programs involving expressions, assignments, and console input/output (I/O). The details of assignments and expressions are similar to those of most other high-level languages. Every language has its own console I/O syntax, so if you are not familiar with C++, that may look new and different to you.

1.1

Introduction to C++ Language is the only instrument of science. SAMUEL JOHNSON

This section gives an overview of the C++ programming language.

Origins of the C++ Language The C++ programming language can be thought of as the C programming language with classes (and other modern features) added. The C programming language was developed by Dennis Ritchie of AT&T Bell Laboratories in the 1970s. It was first used for writing and maintaining the UNIX operating system. (Up until that time, UNIX systems programs were written either in assembly language or in a language called B, a language developed by Ken Thompson, the originator of UNIX.) C is a generalpurpose language that can be used for writing any sort of program, but its success and popularity are closely tied to the UNIX operating system. If you wanted to maintain your UNIX system, you needed to use C. C and UNIX fit together so well that soon not just systems programs but almost all commercial programs that ran under UNIX were written in the C language. C became so popular that versions of the language were written for other popular operating systems; its use is thus not limited to computers that use UNIX. However, despite its popularity, C was not without its shortcomings.

www.itpub.net

Introduction to C++

The C language is peculiar because it is a high-level language with many of the features of a low-level language. C is somewhere in between the two extremes of a very high-level language and a low-level language, and therein lies both its strengths and its weaknesses. Like (low-level) assembly language, C language programs can directly manipulate the computer’s memory. On the other hand, C has the features of a highlevel language, which makes it easier to read and write than assembly language. This makes C an excellent choice for writing systems programs, but for other programs (and in some sense even for systems programs) C is not as easy to understand as other languages; also, it does not have as many automatic checks as some other high-level languages. To overcome these and other shortcomings of C, Bjarne Stroustrup of AT&T Bell Laboratories developed C++ in the early 1980s. Stroustrup designed C++ to be a better C. Most of C is a subset of C++ and so most C programs are also C++ programs. (The reverse is not true; many C++ programs are definitely not C programs.) Unlike C, C++ has facilities for classes and so can be used for object-oriented programming.

C++ and Object-Oriented Programming Object-oriented programming (OOP) is a currently popular and powerful programming technique. The main characteristics of OOP are encapsulation, inheritance, and polymorphism. Encapsulation is a form of information hiding or abstraction. Inheritance has to do with writing reusable code. Polymorphism refers to a way that a single name can have multiple meanings in the context of inheritance. Having made those statements, we must admit that they will hold little meaning for readers who have not heard of OOP before. However, we will describe all these terms in detail later in this book. C++ accommodates OOP by providing classes, a kind of data type combining both data and algorithms. C++ is not what some authorities would call a “pure OOP language.” C++ tempers its OOP features with concerns for efficiency and what some might call “practicality.” This combination has made C++ currently the most widely used OOP language, although not all of its usage strictly follows the OOP philosophy.

The Character of C++ C++ has classes that allow it to be used as an object-oriented language. It allows for overloading of functions and operators. (All these terms will be explained eventually, so do not be concerned if you do not fully understand some terms.) C++’s connection to the C language gives it a more traditional look than newer object-oriented languages, yet it has more powerful abstraction mechanisms than many other currently popular languages. C++ has a template facility that allows for full and direct implementation of algorithm abstraction. C++ templates allow you to code using parameters for types. The newest C++ standard, and most C++ compilers, allow multiple namespaces to accommodate more reuse of class and function names. The exception handling facilities in C++ are similar to what you would find in other programming languages. Memory management in C++ is similar to that in C. The programmer must allocate his or her own memory and handle his or her own garbage collection. Most compilers will allow

3

4

CHAPTER 1

C++ Basics

you to do C-style memory management in C++ since C is essentially a subset of C++. However, C++ also has its own syntax for a C++ style of memory management, and you are advised to use the C++ style of memory management when coding in C++. This book uses only the C++ style of memory management.

C++ Terminology functions program

All procedure-like entities are called functions in C++. Things that are called procedures, methods, functions, or subprograms in other languages are all called functions in C++. As we will see in the next subsection, a C++ program is basically just a function called main; when you run a program, the run-time system automatically invokes the function named main. Other C++ terminology is pretty much the same as most other programming languages, and in any case, will be explained when each concept is introduced.

A Sample C++ Program VideoNote

Compiling and Running a C++ Program

Display 1.1 contains a simple C++ program and two possible screen displays that might be generated when a user runs the program. A C++ program is really a function definition for a function named main. When the program is run, the function named main is invoked. The body of the function main is enclosed in braces, {}. When the program is run, the statements in the braces are executed. The following two lines set up things so that the libraries with console input and output facilities are available to the program. The details concerning these two lines and related topics are covered in Section 1.3 and in Chapters 9, 11, and 12. #include using namespace std;

int main()

The following line says that main is a function with no parameters that returns an int (integer) value: int main( )

return 0;

Some compilers will allow you to omit the int or replace it with void, which indicates a function that does not return a value. However, the previous form is the most universally accepted way to start the main function of a C++ program. The program ends when the following statement is executed: return 0;

This statement ends the invocation of the function main and returns 0 as the function’s value. According to the ANSI/ISO C++ standard, this statement is not required, but many compilers still require it. Chapter 3 covers all these details about C++ functions.

www.itpub.net

Introduction to C++ Display 1.1

A Sample C++ Program

1 2

#include using namespace std;

3 4 5

int main( ) { int numberOfLanguages;

6 7

cout