1038

Click here to load reader

Object Oriented Programming In C++ 4th Edition By Robert Lafore

  • Upload
    anas-sa

  • View
    630

  • Download
    67

Embed Size (px)

Citation preview

  • Robert Lafore

    800 East 96th St., Indianapolis, Indiana 46240 USA

    Object-Oriented Programming in C++,Fourth Edition

    00 3087 FM 11/29/01 2:15 PM Page i

  • Copyright 2002 by Sams PublishingAll rights reserved. No part of this book shall be reproduced, stored in aretrieval system, or transmitted by any means, electronic, mechanical, photo-copying, recording, or otherwise, without written permission from the pub-lisher. No patent liability is assumed with respect to the use of the informationcontained herein. Although every precaution has been taken in the preparationof this book, the publisher and author assume no responsibility for errors oromissions. Nor is any liability assumed for damages resulting from the use ofthe information contained herein.

    International Standard Book Number: 0-672-32308-7

    Library of Congress Catalog Card Number: 2001094813

    Printed in the United States of America

    First Printing: December 2001

    04 03 02 01 4 3 2 1

    TrademarksAll terms mentioned in this book that are known to be trademarks or servicemarks have been appropriately capitalized. Sams Publishing cannot attest tothe accuracy of this information. Use of a term in this book should not beregarded as affecting the validity of any trademark or service mark.

    Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied. The information provided is onan as is basis. The author and the publisher shall have neither liability norresponsibility to any person or entity with respect to any loss or damagesarising from the information contained in this book.

    EXECUTIVE EDITORMichael Stephens

    ACQUISITIONS EDITORMichael Stephens

    MANAGING EDITORMatt Purcell

    PROJECT EDITORSAngela Boley

    Christina Smith

    INDEXERRebecca Salerno

    PROOFREADERMatt Wynalda

    TECHNICAL EDITORMark Cashman

    TEAM COORDINATORPamalee Nelson

    MEDIA DEVELOPERDan Scherf

    INTERIOR DESIGNERGary Adair

    COVER DESIGNERAlan Clements

    PAGE LAYOUTAyanna Lacey

    00 3087 FM 11/29/01 2:15 PM Page ii

  • OverviewIntroduction 1

    1 The Big Picture 9

    2 C++ Programming Basics 29

    3 Loops and Decisions 75

    4 Structures 131

    5 Functions 161

    6 Objects and Classes 215

    7 Arrays and Strings 263

    8 Operator Overloading 319

    9 Inheritance 371

    10 Pointers 429

    11 Virtual Functions 503

    12 Streams and Files 567

    13 Multifile Programs 633

    14 Templates and Exceptions 681

    15 The Standard Template Library 725

    16 Object-Oriented Software Development 801

    A ASCII Chart 849

    B C++ Precedence Table and Keywords 859

    C Microsoft Visual C++ 863

    D Borland C++Builder 871

    E Console Graphics Lite 881

    F STL Algorithms and Member Functions 895

    G Answers to Questions and Exercises 913

    H Bibliography 977

    Index 981

    00 3087 FM 11/29/01 2:15 PM Page iii

  • ContentsIntroduction 1

    1 The Big Picture 9Why Do We Need Object-Oriented Programming? ..............................10

    Procedural Languages ......................................................................10The Object-Oriented Approach ........................................................13

    Characteristics of Object-Oriented Languages......................................16Objects ..............................................................................................16Classes ..............................................................................................18Inheritance ........................................................................................18Reusability ........................................................................................21Creating New Data Types ................................................................21Polymorphism and Overloading ......................................................21

    C++ and C..............................................................................................22Laying the Groundwork ........................................................................23The Unified Modeling Language (UML)..............................................23Summary ................................................................................................25Questions................................................................................................25

    2 C++ Programming Basics 29Getting Started ......................................................................................30Basic Program Construction ..................................................................30

    Functions ..........................................................................................31Program Statements..........................................................................32Whitespace........................................................................................33

    Output Using cout ................................................................................33String Constants................................................................................34

    Directives ..............................................................................................35Preprocessor Directives ....................................................................35Header Files......................................................................................35The using Directive..........................................................................36

    Comments ..............................................................................................36Comment Syntax ..............................................................................36When to Use Comments ..................................................................37Alternative Comment Syntax ..........................................................37

    Integer Variables ....................................................................................38Defining Integer Variables................................................................38Declarations and Definitions ............................................................40Variable Names ................................................................................40Assignment Statements ....................................................................40

    00 3087 FM 11/29/01 2:15 PM Page iv

  • Integer Constants ..............................................................................41Output Variations ..............................................................................41The endl Manipulator ......................................................................41Other Integer Types ..........................................................................42

    Character Variables ................................................................................42Character Constants..........................................................................43Initialization......................................................................................44Escape Sequences ............................................................................44

    Input with cin ........................................................................................45Variables Defined at Point of Use ....................................................47Cascading

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITONvi

    3 Loops and Decisions 75Relational Operators ..............................................................................76Loops......................................................................................................78

    The for Loop....................................................................................78Debugging Animation ......................................................................84for Loop Variations..........................................................................84The while Loop................................................................................86Precedence: Arithmetic and Relational Operators ..........................89The do Loop......................................................................................91When to Use Which Loop................................................................93

    Decisions................................................................................................93The if Statement ..............................................................................94The if...else Statement ................................................................98The else...if Construction ..........................................................106The switch Statement ....................................................................107The Conditional Operator ..............................................................111

    Logical Operators ................................................................................114Logical AND Operator ......................................................................115Logical OR Operator........................................................................116Logical NOT Operator ......................................................................117

    Precedence Summary ..........................................................................118Other Control Statements ....................................................................118

    The break Statement ......................................................................119The continue Statement ................................................................121The goto Statement ........................................................................123

    Summary ..............................................................................................123Questions..............................................................................................124Exercises ..............................................................................................126

    4 Structures 131Structures ............................................................................................132

    A Simple Structure ........................................................................132Defining the Structure ....................................................................133Defining a Structure Variable ........................................................134Accessing Structure Members........................................................136Other Structure Features ................................................................137A Measurement Example ..............................................................139Structures Within Structures ..........................................................141A Card Game Example ..................................................................145Structures and Classes ....................................................................148

    Enumerations ......................................................................................148Days of the Week............................................................................148One Thing or Another ....................................................................151

    00 3087 FM 11/29/01 2:15 PM Page vi

  • CONTENTSvii

    Organizing the Cards......................................................................153Specifying Integer Values ..............................................................155Not Perfect......................................................................................155Other Examples ..............................................................................155

    Summary ..............................................................................................156Questions..............................................................................................156Exercises ..............................................................................................158

    5 Functions 161Simple Functions ................................................................................162

    The Function Declaration ..............................................................164Calling the Function ......................................................................164The Function Definition ................................................................164Comparison with Library Functions ..............................................166Eliminating the Declaration............................................................166

    Passing Arguments to Functions..........................................................167Passing Constants ..........................................................................167Passing Variables ............................................................................169Passing by Value ............................................................................170Structures as Arguments ................................................................171Names in the Declaration ..............................................................176

    Returning Values from Functions ........................................................176The return Statement ....................................................................177Returning Structure Variables ........................................................180

    Reference Arguments ..........................................................................182Passing Simple Data Types by Reference ......................................182A More Complex Pass by Reference ............................................185Passing Structures by Reference ....................................................186Notes on Passing by Reference ......................................................188

    Overloaded Functions ..........................................................................188Different Numbers of Arguments ..................................................189Different Kinds of Arguments ........................................................191

    Recursion ............................................................................................193Inline Functions ..................................................................................195Default Arguments ..............................................................................197Scope and Storage Class......................................................................199

    Local Variables ..............................................................................199Global Variables..............................................................................202Static Local Variables ....................................................................204Storage ............................................................................................205

    Returning by Reference ......................................................................206Function Calls on the Left of the Equal Sign ................................207Dont Worry Yet..............................................................................207

    00 3087 FM 11/29/01 2:15 PM Page vii

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITONviii

    const Function Arguments ..................................................................208Summary ..............................................................................................209Questions..............................................................................................210Exercises ..............................................................................................212

    6 Objects and Classes 215A Simple Class ....................................................................................216

    Classes and Objects ........................................................................217Defining the Class ..........................................................................218Using the Class ..............................................................................221Calling Member Functions ............................................................221

    C++ Objects as Physical Objects ........................................................223Widget Parts as Objects..................................................................223Circles as Objects ..........................................................................224

    C++ Objects as Data Types ................................................................226Constructors ........................................................................................227

    A Counter Example ........................................................................228A Graphics Example ......................................................................231Destructors......................................................................................232

    Objects as Function Arguments ..........................................................233Overloaded Constructors ................................................................234Member Functions Defined Outside the Class ..............................236Objects as Arguments ....................................................................237

    The Default Copy Constructor ............................................................238Returning Objects from Functions ......................................................240

    Arguments and Objects ..................................................................241A Card-Game Example........................................................................243Structures and Classes ........................................................................247Classes, Objects, and Memory ............................................................247Static Class Data ..................................................................................249

    Uses of Static Class Data ..............................................................249An Example of Static Class Data ..................................................249Separate Declaration and Definition ..............................................251

    const and Classes ................................................................................252const Member Functions ..............................................................252const Objects ................................................................................255

    What Does It All Mean? ......................................................................256Summary ..............................................................................................257Questions..............................................................................................257Exercises ..............................................................................................259

    00 3087 FM 11/29/01 2:15 PM Page viii

  • CONTENTSix

    7 Arrays and Strings 263Array Fundamentals ............................................................................264

    Defining Arrays ..............................................................................265Array Elements ..............................................................................265Accessing Array Elements..............................................................267Averaging Array Elements ............................................................267Initializing Arrays ..........................................................................268Multidimensional Arrays ................................................................270Passing Arrays to Functions ..........................................................274Arrays of Structures........................................................................277

    Arrays as Class Member Data ............................................................279Arrays of Objects ................................................................................283

    Arrays of English Distances ..........................................................283Arrays of Cards ..............................................................................286

    C-Strings ..............................................................................................290C-String Variables ..........................................................................290Avoiding Buffer Overflow..............................................................292String Constants..............................................................................292Reading Embedded Blanks ............................................................293Reading Multiple Lines ..................................................................294Copying a String the Hard Way ....................................................295Copying a String the Easy Way......................................................296Arrays of Strings ............................................................................297Strings as Class Members ..............................................................298A User-Defined String Type ..........................................................300

    The Standard C++ string Class..........................................................302Defining and Assigning string Objects ........................................302Input/Output with string Objects..................................................304Finding string Objects ..................................................................305Modifying string Objects ............................................................306Comparing string Objects ............................................................307Accessing Characters in string Objects........................................309Other string Functions..................................................................310

    Summary ..............................................................................................310Questions..............................................................................................311Exercises ..............................................................................................313

    8 Operator Overloading 319Overloading Unary Operators..............................................................320

    The operator Keyword ..................................................................322Operator Arguments ......................................................................323

    00 3087 FM 11/29/01 2:15 PM Page ix

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITONx

    Operator Return Values ..................................................................323Nameless Temporary Objects ........................................................325Postfix Notation..............................................................................326

    Overloading Binary Operators ............................................................328Arithmetic Operators ......................................................................328Concatenating Strings ....................................................................332Multiple Overloading ....................................................................334Comparison Operators....................................................................334Arithmetic Assignment Operators ..................................................337The Subscript Operator ([]) ..........................................................340

    Data Conversion ..................................................................................344Conversions Between Basic Types ................................................344Conversions Between Objects and Basic Types ............................345Conversions Between Objects of Different Classes ......................350Conversions: When to Use What....................................................357

    UML Class Diagrams ..........................................................................357Associations....................................................................................357Navigability ....................................................................................358

    Pitfalls of Operator Overloading and Conversion ..............................358Use Similar Meanings ....................................................................358Use Similar Syntax ........................................................................359Show Restraint................................................................................359Avoid Ambiguity ............................................................................360Not All Operators Can Be Overloaded ..........................................360

    Keywords explicit and mutable ........................................................360Preventing Conversions with explicit ..........................................360Changing const Object Data Using mutable ................................362

    Summary ..............................................................................................364Questions..............................................................................................364Exercises ..............................................................................................367

    9 Inheritance 371Derived Class and Base Class ............................................................373

    Specifying the Derived Class ........................................................375Generalization in UML Class Diagrams ........................................375Accessing Base Class Members ....................................................376The protected Access Specifier ....................................................377

    Derived Class Constructors ................................................................380Overriding Member Functions ............................................................382Which Function Is Used? ....................................................................383

    Scope Resolution with Overridden Functions................................384

    00 3087 FM 11/29/01 2:15 PM Page x

  • CONTENTSxi

    Inheritance in the English Distance Class ..........................................384Operation of ENGLEN ......................................................................387Constructors in DistSign ..............................................................387Member Functions in DistSign ....................................................387Abetting Inheritance ......................................................................388

    Class Hierarchies ................................................................................388Abstract Base Class ....................................................................392Constructors and Member Functions ............................................393

    Inheritance and Graphics Shapes ........................................................393Public and Private Inheritance ............................................................396

    Access Combinations ....................................................................397Access Specifiers: When to Use What ..........................................399

    Levels of Inheritance ..........................................................................399Multiple Inheritance ............................................................................403

    Member Functions in Multiple Inheritance....................................404private Derivation in EMPMULT ..........................................................409

    Constructors in Multiple Inheritance..............................................409Ambiguity in Multiple Inheritance ......................................................413Aggregation: Classes Within Classes ..................................................414

    Aggregation in the EMPCONT Program............................................416Composition: A Stronger Aggregation ..........................................420

    Inheritance and Program Development ..............................................420Summary ..............................................................................................421Questions..............................................................................................422Exercises ..............................................................................................424

    10 Pointers 429Addresses and Pointers ........................................................................430The Address-of Operator & ..................................................................431

    Pointer Variables ............................................................................433Syntax Quibbles..............................................................................434Accessing the Variable Pointed To ................................................436Pointer to void ................................................................................439

    Pointers and Arrays..............................................................................440Pointer Constants and Pointer Variables ........................................442

    Pointers and Functions ........................................................................443Passing Simple Variables................................................................443Passing Arrays ................................................................................446Sorting Array Elements ..................................................................448

    Pointers and C-Type Strings ................................................................452Pointers to String Constants ..........................................................452Strings as Function Arguments ......................................................453

    00 3087 FM 11/29/01 2:15 PM Page xi

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITONxii

    Copying a String Using Pointers....................................................454Library String Functions ................................................................456The const Modifier and Pointers ..................................................456Arrays of Pointers to Strings ..........................................................456

    Memory Management: new and delete ..............................................458The new Operator ............................................................................459The delete Operator ......................................................................461A String Class Using new ..............................................................462

    Pointers to Objects ..............................................................................464Referring to Members ....................................................................465Another Approach to new ..............................................................465An Array of Pointers to Objects ....................................................467

    A Linked List Example........................................................................469A Chain of Pointers ........................................................................469Adding an Item to the List ............................................................471Displaying the List Contents ..........................................................472Self-Containing Classes..................................................................473Augmenting LINKLIST......................................................................473

    Pointers to Pointers ..............................................................................474Sorting Pointers ..............................................................................476The person** Data Type ................................................................476Comparing Strings..........................................................................478

    A Parsing Example ..............................................................................479Parsing Arithmetic Expressions......................................................479The PARSE Program ........................................................................481

    Simulation: A Horse Race ..................................................................484Designing the Horse Race ..............................................................485Multiplicity in the UML ................................................................489

    UML State Diagrams ..........................................................................490States ..............................................................................................491Transitions ......................................................................................491Racing from State to State..............................................................492

    Debugging Pointers..............................................................................492Summary ..............................................................................................493Questions..............................................................................................494Exercises ..............................................................................................497

    11 Virtual Functions 503Virtual Functions..................................................................................504

    Normal Member Functions Accessed with Pointers ......................505Virtual Member Functions Accessed with Pointers ......................507Late Binding ..................................................................................509

    00 3087 FM 11/29/01 2:15 PM Page xii

  • CONTENTSxiii

    Abstract Classes and Pure Virtual Functions ................................510Virtual Functions and the person Class ........................................511Virtual Functions in a Graphics Example ......................................514Virtual Destructors..........................................................................517Virtual Base Classes ......................................................................518

    Friend Functions ..................................................................................520Friends as Bridges ..........................................................................520Breaching the Walls........................................................................522English Distance Example..............................................................522friends for Functional Notation ....................................................526friend Classes................................................................................528

    Static Functions....................................................................................529Accessing static Functions ..........................................................531Numbering the Objects ..................................................................532Investigating Destructors ................................................................532

    Assignment and Copy Initialization ....................................................532Overloading the Assignment Operator ..........................................533The Copy Constructor ....................................................................536UML Object Diagrams ..................................................................539A Memory-Efficient String Class ................................................540

    The this Pointer ..................................................................................547Accessing Member Data with this................................................547Using this for Returning Values....................................................548Revised STRIMEM Program..............................................................550

    Dynamic Type Information..................................................................553Checking the Type of a Class with dynamic_cast ........................553Changing Pointer Types with dynamic_cast..................................554The typeid Operator ......................................................................556

    Summary ..............................................................................................557Questions..............................................................................................558Exercises ..............................................................................................561

    12 Streams and Files 567Stream Classes ....................................................................................568

    Advantages of Streams ..................................................................568The Stream Class Hierarchy ..........................................................568The ios Class ................................................................................570The istream Class ..........................................................................574The ostream Class ..........................................................................575The iostream and the _withassign Classes ..................................576

    Stream Errors ......................................................................................577Error-Status Bits ............................................................................577Inputting Numbers..........................................................................578

    00 3087 FM 11/29/01 2:15 PM Page xiii

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITON

    Too Many Characters ....................................................................579No-Input Input ................................................................................579Inputting Strings and Characters ....................................................580Error-Free Distances ......................................................................580

    Disk File I/O with Streams ..................................................................583Formatted File I/O ..........................................................................583Strings with Embedded Blanks ......................................................586Character I/O ..................................................................................588Binary I/O ......................................................................................589The reinterpret_cast Operator....................................................591Closing Files ..................................................................................591Object I/O ......................................................................................591I/O with Multiple Objects ..............................................................594

    File Pointers ........................................................................................597Specifying the Position ..................................................................598Specifying the Offset ......................................................................598The tellg() Function ....................................................................601

    Error Handling in File I/O ..................................................................601Reacting to Errors ..........................................................................601Analyzing Errors ............................................................................602

    File I/O with Member Functions ........................................................604Objects That Read and Write Themselves ....................................604Classes That Read and Write Themselves ....................................607

    Overloading the Extraction and Insertion Operators ..........................616Overloading for cout and cin ........................................................616Overloading for Files......................................................................618

    Memory as a Stream Object ................................................................620Command-Line Arguments..................................................................622Printer Output ......................................................................................624Summary ..............................................................................................626Questions..............................................................................................627Exercises ..............................................................................................628

    13 Multifile Programs 633Reasons for Multifile Programs ..........................................................634

    Class Libraries ................................................................................634Organization and Conceptualization ..............................................635

    Creating a Multifile Program ..............................................................637Header Files....................................................................................637Directory ........................................................................................637Projects ..........................................................................................637

    xiv

    00 3087 FM 11/29/01 2:15 PM Page xiv

  • CONTENTS

    Inter-File Communication....................................................................638Communication Among Source Files ............................................638Header Files....................................................................................643Namespaces ....................................................................................647

    A Very Long Number Class ................................................................651Numbers as Strings ........................................................................652The Class Specifier ........................................................................652The Member Functions ..................................................................654The Application Program ..............................................................657

    A High-Rise Elevator Simulation ........................................................658Running the ELEV Program ............................................................658Designing the System ....................................................................660Listings for ELEV ............................................................................662Elevator Strategy ............................................................................674State Diagram for the ELEV Program..............................................675

    Summary ..............................................................................................676Questions..............................................................................................677Projects ................................................................................................679

    14 Templates and Exceptions 681Function Templates..............................................................................682

    A Simple Function Template..........................................................684Function Templates with Multiple Arguments ..............................686

    Class Templates ..................................................................................690Class Name Depends on Context ..................................................694A Linked List Class Using Templates............................................696Storing User-Defined Data Types ..................................................698The UML and Templates................................................................702

    Exceptions............................................................................................703Why Do We Need Exceptions? ......................................................703Exception Syntax............................................................................704A Simple Exception Example ........................................................706Multiple Exceptions........................................................................710Exceptions with the Distance Class ..............................................712Exceptions with Arguments............................................................714The bad_alloc Class ......................................................................717Exception Notes..............................................................................718

    Summary ..............................................................................................720Questions..............................................................................................720Exercises ..............................................................................................722

    xv

    00 3087 FM 11/29/01 2:15 PM Page xv

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITON

    15 The Standard Template Library 725Introduction to the STL ......................................................................726

    Containers ......................................................................................727Algorithms ......................................................................................732Iterators ..........................................................................................733Potential Problems with the STL ..................................................734

    Algorithms ..........................................................................................735The find() Algorithm ....................................................................735The count() Algorithm ..................................................................736The sort() Algorithm ....................................................................737The search() Algorithm ................................................................737The merge() Algorithm ..................................................................738Function Objects ............................................................................739The for_each() Algorithm ............................................................742The transform() Algorithm ..........................................................742

    Sequence Containers............................................................................743Vectors ............................................................................................743Lists ................................................................................................747Deques ............................................................................................750

    Iterators ................................................................................................751Iterators as Smart Pointers..............................................................752Iterators as an Interface ..................................................................753Matching Algorithms with Containers ..........................................755Iterators at Work ............................................................................759

    Specialized Iterators ............................................................................763Iterator Adapters ............................................................................763Stream Iterators ..............................................................................767

    Associative Containers ........................................................................771Sets and Multisets ..........................................................................771Maps and Multimaps ......................................................................775

    Storing User-Defined Objects..............................................................778A Set of person Objects ................................................................778A List of person Objects ................................................................782

    Function Objects ..................................................................................786Predefined Function Objects ..........................................................786Writing Your Own Function Objects..............................................789Function Objects Used to Modify Container Behavior ................794

    Summary ..............................................................................................794Questions..............................................................................................795Exercises ..............................................................................................797

    xvi

    00 3087 FM 11/29/01 2:15 PM Page xvi

  • CONTENTS

    16 Object-Oriented Software Development 801Evolution of the Software Development Processes ............................802

    The Seat-of-the-Pants Process........................................................802The Waterfall Process ....................................................................802Object-Oriented Programming ......................................................803Modern Processes ..........................................................................803

    Use Case Modeling..............................................................................805Actors..............................................................................................805Use Cases........................................................................................806Scenarios ........................................................................................806Use Case Diagrams ........................................................................806Use Case Descriptions....................................................................807From Use Cases to Classes ............................................................808

    The Programming Problem..................................................................809Hand-Written Forms ......................................................................809Assumptions ..................................................................................811

    The Elaboration Phase for the LANDLORD Program ............................812Actors..............................................................................................812Use Cases........................................................................................812Use Case Descriptions....................................................................813Scenarios ........................................................................................815UML Activity Diagrams ................................................................815

    From Use Cases to Classes..................................................................816Listing the Nouns ..........................................................................816Refining the List ............................................................................817Discovering Attributes ....................................................................818From Verbs to Messages ................................................................818Class Diagram ................................................................................820Sequence Diagrams ........................................................................820

    Writing the Code..................................................................................824The Header File ..............................................................................825The .CPP Files..................................................................................831More Simplifications ......................................................................841

    Interacting with the Program ..............................................................841Final Thoughts ....................................................................................843Summary ..............................................................................................844Questions..............................................................................................844Projects ................................................................................................846

    A ASCII Chart 849

    B C++ Precedence Table and Keywords 859Precedence Table ................................................................................860Keywords ............................................................................................860

    xvii

    00 3087 FM 11/29/01 2:15 PM Page xvii

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITON

    C Microsoft Visual C++ 863Screen Elements ..................................................................................864Single-File Programs ..........................................................................864

    Building an Existing File................................................................864Writing a New File ........................................................................865Errors ..............................................................................................865Run-Time Type Information (RTTI) ..............................................866

    Multifile Programs ..............................................................................866Projects and Workspaces ................................................................866Developing the Project ..................................................................867Saving, Closing, and Opening Projects..........................................868Compiling and Linking ..................................................................868

    Building Console Graphics Lite Programs..........................................868Debugging............................................................................................868

    Single-Stepping ..............................................................................869Watching Variables ........................................................................869Stepping Into Functions..................................................................869Breakpoints ....................................................................................870

    D Borland C++Builder 871Running the Example Programs in C++Builder..................................872Cleaning Up the Screen ......................................................................873Creating a New Project ........................................................................873Naming and Saving a Project ..............................................................874Starting with Existing Files ................................................................875Compiling, Linking, and Executing ....................................................875

    Executing from C++Builder ..........................................................875Executing from MS-DOS ..............................................................875Precompiled Header Files ..............................................................876Closing and Opening Projects ........................................................876

    Adding a Header File to Your Project ................................................876Creating a New Header File ..........................................................876Editing an Existing Header File ....................................................876Telling C++Builder the Header Files Location ............................877

    Projects with Multiple Source Files ....................................................877Creating Additional Source Files ..................................................877Adding Existing Source Files to Your Project ..............................877The Project Manager ......................................................................878

    Console Graphics Lite Programs ........................................................878Debugging............................................................................................878

    Single-Stepping ..............................................................................879Watching Variables ........................................................................879Tracing into Functions....................................................................879Breakpoints ....................................................................................879

    xviii

    00 3087 FM 11/29/01 2:15 PM Page xviii

  • CONTENTS

    E Console Graphics Lite 881Using the Console Graphics Lite Routines ........................................882The Console Graphics Lite Functions ................................................883Implementations of the Console Graphics Lite Functions ..................884

    Microsoft Compilers ......................................................................885Borland Compilers..........................................................................885

    Source Code Listings ..........................................................................885Listing for MSOFTCON.H ..................................................................886Listing for MSOFTCON.CPP ..............................................................886Listing for BORLACON.H ..................................................................890Listing for BORLACON.CPP ..............................................................891

    F STL Algorithms and Member Functions 895Algorithms ..........................................................................................896Member Functions ..............................................................................907Iterators ................................................................................................909

    G Answers to Questions and Exercises 913Chapter 1..............................................................................................914

    Answers to Questions ....................................................................914Chapter 2..............................................................................................914

    Answers to Questions ....................................................................914Solutions to Exercises ....................................................................916

    Chapter 3..............................................................................................917Answers to Questions ....................................................................917Solutions to Exercises ....................................................................918

    Chapter 4..............................................................................................921Answers to Questions ....................................................................921Solutions to Exercises ....................................................................922

    Chapter 5..............................................................................................924Answers to Questions ....................................................................924Solutions to Exercises ....................................................................925

    Chapter 6..............................................................................................928Answers to Questions ....................................................................928Solutions to Exercises ....................................................................929

    Chapter 7..............................................................................................932Answers to Questions ....................................................................932Solutions to Exercises ....................................................................933

    Chapter 8..............................................................................................937Answers to Questions ....................................................................937Solutions to Exercises ....................................................................938

    Chapter 9..............................................................................................943Answers to Questions ....................................................................943Solutions to Exercises ....................................................................944

    xix

    00 3087 FM 11/29/01 2:15 PM Page xix

  • Chapter 10............................................................................................949Answers to Questions ....................................................................949Solutions to Exercises ....................................................................950

    Chapter 11............................................................................................954Answers to Questions ....................................................................954Solutions to Exercises ....................................................................956

    Chapter 12............................................................................................960Answers to Questions ....................................................................960Solutions to Exercises ....................................................................961

    Chapter 13............................................................................................963Answers to Questions ....................................................................963

    Chapter 14............................................................................................964Answers to Questions ....................................................................964Solutions to Exercises ....................................................................965

    Chapter 15............................................................................................969Answers to Questions ....................................................................969Solutions to Exercises ....................................................................970

    Chapter 16............................................................................................974Answers to Questions ....................................................................974

    H Bibliography 977Advanced C++ ....................................................................................978Defining Documents ............................................................................978The Unified Modeling Language ........................................................978The History of C++ ............................................................................979Other Topics ........................................................................................979

    Index 981

    00 3087 FM 11/29/01 2:15 PM Page xx

  • PrefaceThe major changes to this Fourth Edition include an earlier introduction to UML, a new section on inter-file communication in Chapter 13, and a revised approach to software develop-ment in Chapter 16.

    Introducing the UML at the beginning allows the use of UML diagrams where they fit naturally with topics in the text, so there are many new UML diagrams throughout the book.The section on inter-file communication gathers together many concepts that were previouslyscattered throughout the book. The industrys approach to object-oriented analysis and designhas evolved since the last edition, and accordingly weve modified the chapter on this topic toreflect recent developments.

    C++ itself has changed very little since the last edition. However, besides the revisions justmentioned, weve made many smaller changes to clarify existing topics and correct typos andinaccuracies in the text.

    00 3087 FM 11/29/01 2:15 PM Page xxi

  • About the AuthorRobert Lafore has been writing books about computer programming since 1982. His best-selling titles include Assembly Language Programming for the IBM PC, C Programming UsingTurbo C++, C++ Interactive Course, and Data Structures and Algorithms in Java. Mr. Laforeholds degrees in mathematics and electrical engineering, and has been active in programmingsince the days of the PDP-5, when 4K of main memory was considered luxurious. His interestsinclude hiking, windsurfing, and recreational mathematics.

    00 3087 FM 11/29/01 2:15 PM Page xxii

  • DedicationThis book is dedicated to GGL and her indomitable spirit.

    Acknowledgments to the Fourth EditionMy thanks to many readers who e-mailed comments and corrections. I am also indebted to thefollowing professors of computer science who offered their suggestions and corrections: BillBlomberg of Regis University in Denver; Richard Daehler-Wilking of the College ofCharleston in South Carolina; Frank Hoffmann of the Royal Institute of Technology inSweden, and David Blockus of San Jose State University in California. My special thanks toDavid Topham of Ohlone College in Fremont, California, for his many detailed ideas and hissharp eye for problems.

    At Sams Publishing, Michael Stephens provided an expert and friendly liaison with the detailsof publishing. Reviewer Robin Rowe and Technical Editor Mark Cashman attempted withgreat care to save me from myself; any lack of success is entirely my fault. Project ManagerChristina Smith made sure that everything came together in an amazingly short time, AngelaBoley helped keep everything moving smoothly, and Matt Wynalda provided expert proofread-ing. Im grateful to you all.

    Acknowledgments to the Third EditionId like to thank the entire team at MacMillan Computer Publishing. In particular, TracyDunkelberger ably spearheaded the entire project and exhibited great patience with whatturned out to be a lengthy schedule. Jeff Durham handled the myriad details involved in inter-facing between me and the editors with skill and good humor. Andrei Kossorouko lent hisexpertise in C++ to ensure that I didnt make this edition worse instead of better.

    Acknowledgments to the Second EditionMy thanks to the following professorsusers of this book as a text at their respective collegesand universitiesfor their help in planning the second edition: Dave Bridges, Frank Cioch,Jack Davidson, Terrence Fries, Jimmie Hattemer, Jack Van Luik, Kieran Mathieson, BillMcCarty, Anita Millspaugh, Ian Moraes, Jorge Prendes, Steve Silva, and Edward Wright.

    I would like to thank the many readers of the first edition who wrote in with corrections andsuggestions, many of which were invaluable.

    At Waite Group Press, Joanne Miller has ably ridden herd on my errant scheduling and filledin as academic liaison, and Scott Calamar, as always, has made sure that everyone knew whatthey were doing. Deirdre Greene provided an uncannily sharp eye as copy editor.

    00 3087 FM 11/29/01 2:15 PM Page xxiii

  • Thanks, too, to Mike Radtke and Harry Henderson for their expert technical reviews.

    Special thanks to Edward Wright, of Western Oregon State College, for reviewing and experi-menting with the new exercises.

    Acknowledgments to the First EditionMy primary thanks go to Mitch Waite, who poured over every inch of the manuscript withpainstaking attention to detail and made a semi-infinite number of helpful suggestions.

    Bill McCarty of Azusa Pacific University reviewed the content of the manuscript and its suit-ability for classroom use, suggested many excellent improvements, and attempted to correctmy dyslexic spelling.

    George Leach ran all the programs, and, to our horror, found several that didnt perform cor-rectly in certain circumstances. I trust these problems have all been fixed; if not, the fault isentirely mine.

    Scott Calamar of the Waite Group dealt with the myriad organizational aspects of writing andproducing this book. His competence and unfailing good humor were an important ingredientin its completion.

    I would also like to thank Nan Borreson of Borland for supplying the latest releases of thesoftware (among other useful tidbits), Harry Henderson for reviewing the exercises, LouiseOrlando of the Waite Group for ably shepherding the book through production, MerrillPeterson of Matrix Productions for coordinating the most trouble-free production run Ive everbeen involved with, Juan Vargas for the innovative design, and Frances Hasegawa for heruncanny ability to decipher my sketches and produce beautiful and effective art.

    00 3087 FM 11/29/01 2:15 PM Page xxiv

  • Tell Us What You Think!As the reader of this book, you are our most important critic and commentator. We value youropinion and want to know what were doing right, what we could do better, what areas youdlike to see us publish in, and any other words of wisdom youre willing to pass our way.

    As an executive editor for Sams Publishing, I welcome your comments. You cane-mailor write me directly to let me know what you did or didnt like about this bookas well aswhat we can do to make our books stronger.

    Please note that I cannot help you with technical problems related to the topic of this book,and that due to the high volume of mail I receive, I might not be able to reply to every mes-sage.

    When you write, please be sure to include this books title and authors name as well as yourname and phone or fax number. I will carefully review your comments and share them with theauthor and editors who worked on the book.

    E-mail: [email protected]

    Mail:

    Sams Publishing201 West 103rd StreetIndianapolis, IN 46290 USA

    00 3087 FM 11/29/01 2:15 PM Page xxv

  • IntroductionThis book teaches you how to write programs in a the C++ programming language. However,it does more than that. In the past few years, several major innovations in software develop-ment have appeared on the scene. This book teaches C++ in the context of these new develop-ments. Lets see what they are.

    Programming InnovationsIn the old days, 20 or so years ago, programmers starting a project would sit down almostimmediately and start writing code. However, as programming projects became large and morecomplicated, it was found that this approach did not work very well. The problem was com-plexity.

    Large programs are probably the most complicated entities ever created by humans. Becauseof this complexity, programs are prone to error, and software errors can be expensive and evenlife threatening (in air traffic control, for example). Three major innovations in programminghave been devised to cope with the problem of complexity. They are

    Object-oriented programming (OOP)

    The Unified Modeling Language (UML)

    Improved software development processes

    This book teaches the C++ language with these developments in mind. You will not only learna computer language, but new ways of conceptualizing software development.

    Object-Oriented ProgrammingWhy has object-oriented programming become the preferred approach for most software pro-jects? OOP offers a new and powerful way to cope with complexity. Instead of viewing a pro-gram as a series of steps to be carried out, it views it as a group of objects that have certainproperties and can take certain actions. This may sound obscure until you learn more about it,but it results in programs that are clearer, more reliable, and more easily maintained.

    A major goal of this book is to teach object-oriented programming. We introduce it as early aspossible, and cover all its major features. The majority of our example programs are object-oriented.

    The Unified Modeling LanguageThe Unified Modeling Language (UML) is a graphical language consisting of many kinds ofdiagrams. It helps program analysts figure out what a program should do, and helps program-mers design and understand how a program works. The UML is a powerful tool that can makeprogramming easier and more effective.

    01 3087 Intro 11/29/01 2:23 PM Page 1

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITION

    We give an overview of the UML in Chapter 1, and then discuss specific features of the UMLthroughout the book. We introduce each UML feature where it will help to clarify the OOPtopic being discussed. In this way you learn the UML painlessly at the same time the UMLhelps you to learn C++.

    Languages and Development PlatformsOf the object-oriented programming languages, C++ is by far the most widely used. Java, arecent addition to the field of OO languages, lacks certain featuressuch as pointers, tem-plates, and multiple inheritancethat make it less powerful and versatile than C++. (If youever do want to learn Java, its syntax is very similar to that of C++, so learning C++ gives youa head start in Java.)

    Several other OO languages have been introduced recently, such as C#, but they have not yetattained the wide acceptance of C++.

    Until recently the standards for C++ were in a constant state of evolution. This meant that eachcompiler vendor handled certain details differently. However, in November 1997, theANSI/ISO C++ standards committee approved the final draft of what is now known asStandard C++. (ANSI stands for American National Standards Institute, and ISO stands forInternational Standards Institute.) Standard C++ adds many new features to the language, suchas the Standard Template Library (STL). In this book we follow Standard C++ (in all but a fewplaces, which well note as we go along).

    The most popular development environments for C++ are manufactured by Microsoft andBorland (Inprise) and run on the various flavors of Microsoft Windows. In this book weveattempted to ensure that all sample programs run on the current versions of both Borland andMicrosoft compilers. (See Appendix C, Microsoft Visual C++, and Appendix D, BorlandC++Builder, for more on these compilers.)

    What This Book DoesThis book teaches object-oriented programming with the C++ programming language, usingeither Microsoft or Borland compilers. It also introduces the UML and software developmentprocesses. It is suitable for professional programmers, students, and kitchen-table enthusiasts.

    New ConceptsOOP involves concepts that are new to programmers of traditional languages such as Pascal,Basic, and C. These ideas, such as classes, inheritance, and polymorphism, lie at the heart ofobject-oriented programming. But its easy to lose sight of these concepts when discussing thespecifics of an object-oriented language. Many books overwhelm the reader with the details oflanguage features, while ignoring the reason these features exist. This book attempts to keep aneye on the big picture and relate the details to the larger concepts.

    2

    01 3087 Intro 11/29/01 2:23 PM Page 2

  • INTRODUCTION

    The Gradual ApproachWe take a gradual approach in this book, starting with very simple programming examples andworking up to full-fledged object-oriented applications. We introduce new concepts slowly sothat you will have time to digest one idea before going on to the next. We use illustrationswhenever possible to help clarify new ideas. There are questions and programming exercises atthe end of most chapters to enhance the books usefulness in the classroom. Answers to thequestions and to the first few (starred) exercises can be found in Appendix G. The exercisesvary in difficulty to pose a variety of challenges for the student.

    What You Need to Know to Use This BookYou can use this book even if you have no previous programming experience. However, suchexperience, in Visual Basic for example, certainly wont hurt.

    You do not need to know the C language to use this book. Many books on C++ assume thatyou already know C, but this one does not. It teaches C++ from the ground up. If you do knowC, it wont hurt, but you may be surprised at how little overlap there is between C and C++.

    You should be familiar with the basic operations of Microsoft Windows, such as starting appli-cations and copying files.

    Software and HardwareYou will need a C++ compiler. The programs in this book have been tested with MicrosoftVisual C++ and Borland C++Builder. Both compilers come in low-priced Learning Editionssuitable for students.

    Appendix C provides detailed information on operating the Microsoft compiler, whileAppendix D does the same for the Inprise (Borland) product. Other compilers, if they adhereto Standard C++, will probably handle most of the programs in this book as written.

    Your computer should have enough processor speed, memory, and hard disk space to run thecompiler youve chosen. You can check the manufacturers specifications to determine theserequirements.

    Console-Mode ProgramsThere are numerous example programs throughout the book. They are console-mode programs,which run in a character-mode window within the compiler environment, or directly within anMS-DOS box. This avoids the complexity of full-scale graphics-oriented Windows programs.

    3

    01 3087 Intro 11/29/01 2:23 PM Page 3

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITION

    Example Program Source CodeYou can obtain the source code for the example programs from the Sams Publishing Web site at

    http://www.samspublishing.com

    Type the ISBN (found at the front of the book) or the books title and click Search to find thedata on this book. Then click Source Code to download the program examples.

    Console Graphics LiteA few example programs draw pictures using a graphics library we call Console Graphics Lite.The graphics rely on console characters, so they are not very sophisticated, but they allowsome interesting programs. The files for this library are provided on the publishers Web site,along with the source files for the example programs.

    To compile and run these graphics examples, youll need to include a header file in your pro-gram, either MSOFTCON.H or BORLACON.H, depending on your compiler. Youll also need to addeither MSOFTCON.CPP or BORLACON.CPP to the project for the graphics example. Appendix E,Console Graphics Lite, provides listings of these files and tells how to use them. AppendixesC and D explain how to work with files and projects in a specific compilers environment.

    Programming ExercisesEach chapter contains roughly 12 exercises, each requiring the creation of a complete C++program. Solutions for the first three or four exercises in each chapter are provided inAppendix G. For the remainder of the exercises, readers are on their own. (However, if you areteaching a C++ course, see the Note to Teachers at the end of this Introduction.)

    Easier Than You ThinkYou may have heard that C++ is difficult to learn, but its really quite similar to other lan-guages, with two or three grand ideas thrown in. These new ideas are fascinating in them-selves, and we think youll have fun learning about them. They are also becoming part of theprogramming culture; theyre something everyone should know a little bit about, like evolutionand psychoanalysis. We hope this book will help you enjoy learning about these new ideas, atthe same time that it teaches you the details of programming in C++.

    4

    01 3087 Intro 11/29/01 2:23 PM Page 4

  • INTRODUCTION

    A Note to TeachersTeachers, and others who already know something about C++ or C, may be interested in somedetails of the approach we use in this book and how its organized.

    Standard C++All the programs in this book are compatible with Standard C++, with a few minor exceptionsthat are needed to accommodate compiler quirks. We devote a chapter to the STL (StandardTemplate Library), which is included in Standard C++.

    The Unified Modeling Language (UML)In the previous edition, we introduced the UML in the final chapter. In this edition we haveintegrated the UML into the body of the book, introducing UML topics in appropriate places.For example, UML class diagrams are introduced where we first show different classes com-municating, and generalization is covered in the chapter on inheritance.

    Chapter 1, The Big Picture, includes a list showing where the various UML topics are intro-duced.

    Software Development ProcessesFormal software development processes are becoming an increasingly important aspect of pro-gramming. Also, students are frequently mystified by the process of designing an object-oriented program. For these reasons we include a chapter on software development processes,with an emphasis on object-oriented programming. In the last edition we focused on CRCcards, but the emphasis in software development has shifted more in the direction of use case analysis, so we use that to analyze our programming projects.

    C++ Is Not the Same as CA few institutions still want their students to learn C before learning C++. In our view this is amistake. C and C++ are entirely separate languages. Its true that their syntax is similar, and Cis actually a subset of C++. But the similarity is largely a historical accident. In fact, the basicapproach in a C++ program is radically different from that in a C program.

    C++ has overtaken C as the preferred language for serious software development. Thus wedont believe it is necessary or advantageous to teach C before teaching C++. Students whodont know C are saved the time and trouble of learning C and then learning C++, an ineffi-cient approach. Students who already know C may be able to skim parts of some chapters, butthey will find that a remarkable percentage of the material is new.

    5

    01 3087 Intro 11/29/01 2:23 PM Page 5

  • OBJECT-ORIENTED PROGRAMMING IN C++, FOURTH EDITION

    Optimize Organization for OOPWe could have begun the book by teaching the procedural concepts common to C and C++,and moved on to the new OOP concepts once the procedural approach had been digested. Thatseemed counterproductive, however, because one of our goals is to begin true object-orientedprogramming as quickly as possible. Accordingly, we provide a minimum of proceduralgroundwork before getting to classes in Chapter 6. Even the initial chapters are heavily steepedin C++, as opposed to C, usage.

    We introduce some concepts earlier than is traditional in books on C. For example, structuresare a key feature for understanding C++ because classes are syntactically an extension of struc-tures. For this reason, we introduce structures in Chapter 5 so that they will be familiar whenwe discuss classes.

    Some concepts, such as pointers, are introduced later than in traditional C books. Its not nec-essary to understand pointers to follow the essentials of OOP, and pointers are usually a stum-bling block for C and C++ students. Therefore, we defer a discussion of pointers until the mainconcepts of OOP have been thoroughly digested.

    Substitute Superior C++ FeaturesSome features of C have been superseded by new approaches in C++. For instance, theprintf() and scanf() functions, input/output workhorses in C, are seldom used in C++because cout and cin do a better job. Consequently, we leave out descriptions of these func-tions. Similarly, #define constants and macros in C have been largely superseded by the constqualifier and inline functions in C++, and need be mentioned only briefly.

    Minimize Irrelevant CapabilitiesBecause the focus in this book is on object-oriented programming, we can leave out some fea-tures of C that are seldom used and are not particularly relevant to OOP. For instance, it isntnecessary to understand the C bit-wise operators (used to operate on individual bits) to learnobject-oriented programming. These and a few other features can be dropped from our discus-sion, or mentioned only briefly, with no loss in understanding of the major features of C++.

    The result is a book that focuses on the fundamentals of OOP, moving the reader gently butbriskly toward an understanding of new concepts and their application to real programmingproblems.

    6

    01 3087 Intro 11/29/01 2:23 PM Page 6

  • INTRODUCTION

    Programming ExercisesNo answers to the unstarred exercises are provided in this book. However, qualified instructorscan obtain suggested solutions from the Sams Publishing Web site. Type the ISBN or title andclick Search to move to this books page, then click Downloads.

    The exercises vary considerably in their degree of difficulty. In each chapter the early exercisesare fairly easy, while later ones are more challenging. Instructors will probably want to assignonly those exercises suited to the level of a particular class.

    7

    01 3087 Intro 11/29/01 2:23 PM Page 7

  • 01 3087 Intro 11/29/01 2:23 PM Page 8

  • CHAPTER

    1The Big Picture

    IN THIS CHAPTER Why Do We Need Object-Oriented

    Programming? 10

    Characteristics of Object-Oriented Languages 16

    C++ and C 22

    Laying the Groundwork 23

    The Unified Modeling Language (UML) 23

    02 3087 CH01 11/29/01 2:15 PM Page 9

  • Chapter 110

    This book teaches you how to program in C++, a computer language that supports object-oriented programming (OOP). Why do we need OOP? What does it do that traditional lan-guages such as C, Pascal, and BASIC dont? What are the principles behind OOP? Two keyconcepts in OOP are objects and classes. What do these terms mean? What is the relationshipbetween C++ and the older C language?

    This chapter explores these questions and provides an overview of the features to be discussedin the balance of the book. What we say here will necessarily be rather general (although mer-cifully brief). If you find the discussion somewhat abstract, dont worry. The concepts we men-tion here will come into focus as we demonstrate them in detail in subsequent chapters.

    Why Do We Need Object-OrientedProgramming?Object-oriented programming was developed because limitations were discovered inearlier approaches to programming. To appreciate what OOP does, we need to under-stand what these limitations are and how they arose from traditional programminglanguages.

    Procedural LanguagesC, Pascal, FORTRAN, and similar languages are procedural languages. That is, eachstatement in the language tells the computer to do something: Get some input, addthese numbers, divide by six, display that output. A program in a procedural languageis a list of instructions.

    For very small programs, no other organizing principle (often called a paradigm) is needed.The programmer creates the list of instructions, and the computer carries them out.

    Division into FunctionsWhen programs become larger, a single list of instructions becomes unwieldy. Fewprogrammers can comprehend a program of more than a few hundred statementsunless it is broken down into smaller units. For this reason the function was adoptedas a way to make programs more comprehensible to their human creators. (The termfunction is used in C++ and C. In other languages the same concept may be referredto as a subroutine, a subprogram, or a procedure.) A procedural program is dividedinto functions, and (ideally, at least) each function has a clearly defined purpose and aclearly defined interface to the other functions in the program.

    02 3087 CH01 11/29/01 2:15 PM Page 10

  • The idea of breaking a program into functions can be further extended by grouping a numberof functions together into a larger entity called a module (which is often a file), but the princi-ple is similar: a grouping of components that execute lists of instructions.

    Dividing a program into functions and modules is one of the cornerstones of structured pro-gramming, the somewhat loosely defined discipline that influenced programming organizationfor several decades before the advent of object-oriented programming.

    Problems with Structured ProgrammingAs programs grow ever larger and m