Object-oriented programming in C++ [7th print. with corrections ed.]
 0672323087, 9780672323089

Table of contents :
Cover......Page 1
Contents......Page 5
Introduction......Page 28
1 The Big Picture......Page 36
Procedural Languages......Page 37
The Object-Oriented Approach......Page 40
Objects......Page 43
Inheritance......Page 45
Polymorphism and Overloading......Page 48
C++ and C......Page 49
The Unified Modeling Language (UML)......Page 50
Questions......Page 52
2 C++ Programming Basics......Page 56
Basic Program Construction......Page 57
Functions......Page 58
Program Statements......Page 59
Output Using cout......Page 60
String Constants......Page 61
Header Files......Page 62
Comment Syntax......Page 63
Alternative Comment Syntax......Page 64
Defining Integer Variables......Page 65
Assignment Statements......Page 67
The end1 Manipulator......Page 68
Character Variables......Page 69
Character Constants......Page 70
Escape Sequences......Page 71
Input with cin......Page 72
Precedence......Page 74
Type float......Page 75
Type double and long double......Page 76
Floating-Point Constants......Page 77
Type bool......Page 78
The setw Manipulator......Page 79
Variable Type Summary......Page 81
unsigned Data Types......Page 82
Type Conversion......Page 83
Automatic Conversions......Page 84
Casts......Page 85
Arithmetic Operators......Page 87
Arithmetic Assignment Operators......Page 88
Increment Operators......Page 90
Library Functions......Page 92
Library Files......Page 93
Two Ways to Use #include......Page 94
Summary......Page 95
Questions......Page 96
Exercises......Page 98
3 Loops and Decisions......Page 102
Relational Operators......Page 103
The for Loop......Page 105
for Loop Variations......Page 111
The while Loop......Page 113
Precedence: Arithmetic and Relational Operators......Page 116
The do Loop......Page 118
Decisions......Page 120
The if Statement......Page 121
The if...else Statement......Page 125
The else...if Construction......Page 133
The switch Statement......Page 134
The Conditional Operator......Page 138
Logical Operators......Page 141
Logical AND Operator......Page 142
Logical OR Operator......Page 143
Logical NOT Operator......Page 144
Other Control Statements......Page 145
The break Statement......Page 146
The continue Statement......Page 148
Summary......Page 150
Questions......Page 151
Exercises......Page 153
4 Structures......Page 158
A Simple Structure......Page 159
Defining the Structure......Page 160
Defining a Structure Variable......Page 161
Accessing Structure Members......Page 163
Other Structure Features......Page 164
A Measurement Example......Page 166
Structures Within Structures......Page 168
A Card Game Example......Page 172
Days of the Week......Page 175
One Thing or Another......Page 178
Organizing the Cards......Page 180
Other Examples......Page 182
Questions......Page 183
Exercises......Page 185
5 Functions......Page 188
Simple Functions......Page 189
The Function Definition......Page 191
Eliminating the Declaration......Page 193
Passing Constants......Page 194
Passing Variables......Page 196
Passing by Value......Page 197
Structures as Arguments......Page 198
Returning Values from Functions......Page 203
The return Statement......Page 204
Returning Structure Variables......Page 207
Passing Simple Data Types by Reference......Page 209
A More Complex Pass by Reference......Page 212
Passing Structures by Reference......Page 213
Overloaded Functions......Page 215
Different Numbers of Arguments......Page 216
Different Kinds of Arguments......Page 218
Recursion......Page 220
Inline Functions......Page 222
Default Arguments......Page 224
Local Variables......Page 226
Global Variables......Page 229
Static Local Variables......Page 231
Storage......Page 232
Returning by Reference......Page 233
Don't Worry Yet......Page 234
const Function Arguments......Page 235
Summary......Page 236
Questions......Page 237
Exercises......Page 239
6 Objects and Classes......Page 242
A Simple Class......Page 243
Classes and Objects......Page 244
Defining the Class......Page 245
Calling Member Functions......Page 248
Widget Parts as Objects......Page 250
Circles as Objects......Page 251
C++ Objects as Data Types......Page 253
Constructors......Page 254
A Counter Example......Page 255
A Graphics Example......Page 258
Destructors......Page 259
Objects as Function Arguments......Page 260
Overloaded Constructors......Page 261
Member Functions Defined Outside the Class......Page 263
Objects as Arguments......Page 264
The Default Copy Constructor......Page 265
Returning Objects from Functions......Page 267
Arguments and Objects......Page 268
A Card-Game Example......Page 270
Classes, Objects, and Memory......Page 274
An Example of Static Class Data......Page 276
Separate Declaration and Definition......Page 278
const Member Functions......Page 279
const Objects......Page 282
What Does It All Mean?......Page 283
Questions......Page 284
Exercises......Page 286
7 Arrays and Strings......Page 290
Array Fundamentals......Page 291
Array Elements......Page 292
Averaging Array Elements......Page 294
Initializing Arrays......Page 295
Multidimensional Arrays......Page 297
Passing Arrays to Functions......Page 301
Arrays of Structures......Page 304
Arrays as Class Member Data......Page 306
Arrays of English Distances......Page 310
Arrays of Cards......Page 313
C-String Variables......Page 317
String Constants......Page 319
Reading Embedded Blanks......Page 320
Reading Multiple Lines......Page 321
Copying a String the Hard Way......Page 322
Copying a String the Easy Way......Page 323
Arrays of Strings......Page 324
Strings as Class Members......Page 325
A User-Defined String Type......Page 327
Defining and Assigning string Objects......Page 329
Input/Output with string Objects......Page 331
Finding string Objects......Page 332
Modifying string Objects......Page 333
Comparing string Objects......Page 334
Accessing Characters in string Objects......Page 336
Summary......Page 337
Questions......Page 338
Exercises......Page 340
8 Operator Overloading......Page 346
Overloading Unary Operators......Page 347
The operator Keyword......Page 349
Operator Return Values......Page 350
Nameless Temporary Objects......Page 352
Postfix Notation......Page 353
Arithmetic Operators......Page 355
Concatenating Strings......Page 359
Comparison Operators......Page 361
Arithmetic Assignment Operators......Page 364
The Subscript Operator ([])......Page 367
Conversions Between Basic Types......Page 371
Conversions Between Objects and Basic Types......Page 372
Conversions Between Objects of Different Classes......Page 377
Associations......Page 384
Use Similar Meanings......Page 385
Show Restraint......Page 386
Preventing Conversions with explicit......Page 387
Changing const Object Data Using mutable......Page 389
Questions......Page 391
Exercises......Page 394
9 Inheritance......Page 398
Derived Class and Base Class......Page 400
Generalization in UML Class Diagrams......Page 402
Accessing Base Class Members......Page 403
The protected Access Specifier......Page 404
Derived Class Constructors......Page 407
Overriding Member Functions......Page 409
Which Function Is Used?......Page 410
Inheritance in the English Distance Class......Page 411
Member Functions in DistSign......Page 414
Class Hierarchies......Page 415
"Abstract" Base Class......Page 419
Inheritance and Graphics Shapes......Page 420
Public and Private Inheritance......Page 423
Access Combinations......Page 424
Levels of Inheritance......Page 426
Multiple Inheritance......Page 430
Member Functions in Multiple Inheritance......Page 431
Constructors in Multiple Inheritance......Page 436
Ambiguity in Multiple Inheritance......Page 440
Aggregation: Classes Within Classes......Page 441
Aggregation in the EMPCONT Program......Page 443
Inheritance and Program Development......Page 447
Summary......Page 448
Questions......Page 449
Exercises......Page 451
10 Pointers......Page 456
Addresses and Pointers......Page 457
The Address-of Operator &......Page 458
Pointer Variables......Page 460
Syntax Quibbles......Page 461
Accessing the Variable Pointed To......Page 463
Pointer to void......Page 466
Pointers and Arrays......Page 467
Pointer Constants and Pointer Variables......Page 469
Passing Simple Variables......Page 470
Passing Arrays......Page 473
Sorting Array Elements......Page 475
Pointers to String Constants......Page 479
Strings as Function Arguments......Page 480
Copying a String Using Pointers......Page 481
Arrays of Pointers to Strings......Page 483
Memory Management: new and delete......Page 485
The new Operator......Page 486
The delete Operator......Page 488
A String Class Using new......Page 489
Pointers to Objects......Page 491
Another Approach to new......Page 492
An Array of Pointers to Objects......Page 494
A Chain of Pointers......Page 496
Adding an Item to the List......Page 498
Displaying the List Contents......Page 499
Augmenting LINKLIST......Page 500
Pointers to Pointers......Page 501
The person** Data Type......Page 503
Comparing Strings......Page 505
Parsing Arithmetic Expressions......Page 506
The PARSE Program......Page 508
Simulation: A Horse Race......Page 511
Designing the Horse Race......Page 512
Multiplicity in the UML......Page 516
UML State Diagrams......Page 517
Transitions......Page 518
Debugging Pointers......Page 519
Summary......Page 520
Questions......Page 521
Exercises......Page 524
11 Virtual Functions......Page 530
Virtual Functions......Page 531
Normal Member Functions Accessed with Pointers......Page 532
Virtual Member Functions Accessed with Pointers......Page 534
Late Binding......Page 536
Abstract Classes and Pure Virtual Functions......Page 537
Virtual Functions and the person Class......Page 538
Virtual Functions in a Graphics Example......Page 541
Virtual Destructors......Page 544
Virtual Base Classes......Page 545
Friends as Bridges......Page 547
English Distance Example......Page 549
friends for Functional Notation......Page 553
friend Classes......Page 555
Static Functions......Page 556
Accessing static Functions......Page 558
Assignment and Copy Initialization......Page 559
Overloading the Assignment Operator......Page 560
The Copy Constructor......Page 563
UML Object Diagrams......Page 566
A Memory-Efficient String Class......Page 567
Accessing Member Data with this......Page 574
Using this for Returning Values......Page 575
Revised STRIMEM Program......Page 577
Checking the Type of a Class with dynamic_cast......Page 580
Changing Pointer Types with dynamic_cast......Page 581
The typeid Operator......Page 583
Summary......Page 584
Questions......Page 585
Exercises......Page 588
12 Streams and Files......Page 594
The Stream Class Hierarchy......Page 595
The ios Class......Page 597
The istream Class......Page 601
The ostream Class......Page 602
The iostream and the _withassign Classes......Page 603
Error-Status Bits......Page 604
Inputting Numbers......Page 605
No-Input Input......Page 606
Error-Free Distances......Page 607
Formatted File I/O......Page 610
Strings with Embedded Blanks......Page 613
Character I/O......Page 615
Binary I/O......Page 616
Object I/O......Page 618
I/O with Multiple Objects......Page 621
File Pointers......Page 624
Specifying the Offset......Page 625
Reacting to Errors......Page 628
Analyzing Errors......Page 629
Objects That Read and Write Themselves......Page 631
Classes That Read and Write Themselves......Page 634
Overloading for cout and cin......Page 643
Overloading for Files......Page 645
Memory as a Stream Object......Page 647
Command-Line Arguments......Page 649
Printer Output......Page 651
Summary......Page 653
Questions......Page 654
Exercises......Page 655
13 Multifile Programs......Page 660
Class Libraries......Page 661
Organization and Conceptualization......Page 662
Projects......Page 664
Communication Among Source Files......Page 665
Header Files......Page 670
Namespaces......Page 674
A Very Long Number Class......Page 678
The Class Specifier......Page 679
The Member Functions......Page 681
The Application Program......Page 684
Running the ELEV Program......Page 685
Designing the System......Page 687
Listings for ELEV......Page 689
Elevator Strategy......Page 701
State Diagram for the ELEV Program......Page 702
Summary......Page 703
Questions......Page 704
Projects......Page 706
14 Templates and Exceptions......Page 708
Function Templates......Page 709
A Simple Function Template......Page 711
Function Templates with Multiple Arguments......Page 713
Class Templates......Page 717
Class Name Depends on Context......Page 721
A Linked List Class Using Templates......Page 723
Storing User-Defined Data Types......Page 725
The UML and Templates......Page 729
Why Do We Need Exceptions?......Page 730
Exception Syntax......Page 731
A Simple Exception Example......Page 733
Multiple Exceptions......Page 737
Exceptions with the Distance Class......Page 739
Exceptions with Arguments......Page 741
The bad_alloc Class......Page 744
Exception Notes......Page 745
Questions......Page 747
Exercises......Page 749
15 The Standard Template Library......Page 752
Introduction to the STL......Page 753
Containers......Page 754
Algorithms......Page 759
Iterators......Page 760
Potential Problems with the STL......Page 761
The find() Algorithm......Page 762
The count() Algorithm......Page 763
The search() Algorithm......Page 764
The merge() Algorithm......Page 765
Function Objects......Page 766
The transform() Algorithm......Page 769
Vectors......Page 770
Lists......Page 774
Deques......Page 777
Iterators......Page 778
Iterators as Smart Pointers......Page 779
Iterators as an Interface......Page 780
Matching Algorithms with Containers......Page 782
Iterators at Work......Page 786
Iterator Adapters......Page 790
Stream Iterators......Page 794
Sets and Multisets......Page 798
Maps and Multimaps......Page 802
A Set of person Objects......Page 805
A List of person Objects......Page 809
Predefined Function Objects......Page 813
Writing Your Own Function Objects......Page 816
Summary......Page 821
Questions......Page 822
Exercises......Page 824
16 Object-Oriented Software Development......Page 828
The Waterfall Process......Page 829
Modern Processes......Page 830
Actors......Page 832
Use Case Diagrams......Page 833
Use Case Descriptions......Page 834
From Use Cases to Classes......Page 835
Hand-Written Forms......Page 836
Assumptions......Page 838
Use Cases......Page 839
Use Case Descriptions......Page 840
UML Activity Diagrams......Page 842
Listing the Nouns......Page 843
Refining the List......Page 844
From Verbs to Messages......Page 845
Sequence Diagrams......Page 847
Writing the Code......Page 851
The Header File......Page 852
The .CPP Files......Page 858
Interacting with the Program......Page 868
Final Thoughts......Page 870
Questions......Page 871
Projects......Page 873
A: ASCII Chart......Page 876
B: C++ Precedence Table and Keywords......Page 886
Keywords......Page 887
C: Microsoft Visual C++......Page 890
Building an Existing File......Page 891
Errors......Page 892
Projects and Workspaces......Page 893
Developing the Project......Page 894
Debugging......Page 895
Stepping Into Functions......Page 896
Breakpoints......Page 897
D: Borland C++Builder......Page 898
Running the Example Programs in C++Builder......Page 899
Creating a New Project......Page 900
Naming and Saving a Project......Page 901
Executing from MS-DOS......Page 902
Editing an Existing Header File......Page 903
Adding Existing Source Files to Your Project......Page 904
Debugging......Page 905
Breakpoints......Page 906
E: Console Graphics Lite......Page 908
Using the Console Graphics Lite Routines......Page 909
The Console Graphics Lite Functions......Page 910
Implementations of the Console Graphics Lite Functions......Page 911
Source Code Listings......Page 912
Listing for MSOFTCON.CPP......Page 913
Listing for BORLACON.H......Page 917
Listing for BORLACON.CPP......Page 918
F: STL Algorithms and Member Functions......Page 922
Algorithms......Page 923
Member Functions......Page 934
Iterators......Page 936
G: Answers to Questions and Exercises......Page 940
Answers to Questions......Page 941
Solutions to Exercises......Page 943
Answers to Questions......Page 944
Solutions to Exercises......Page 945
Answers to Questions......Page 948
Solutions to Exercises......Page 949
Answers to Questions......Page 951
Solutions to Exercises......Page 952
Answers to Questions......Page 955
Solutions to Exercises......Page 956
Answers to Questions......Page 959
Solutions to Exercises......Page 960
Answers to Questions......Page 964
Solutions to Exercises......Page 965
Answers to Questions......Page 970
Solutions to Exercises......Page 971
Answers to Questions......Page 976
Solutions to Exercises......Page 977
Answers to Questions......Page 981
Solutions to Exercises......Page 983
Answers to Questions......Page 987
Solutions to Exercises......Page 988
Answers to Questions......Page 990
Answers to Questions......Page 991
Solutions to Exercises......Page 992
Answers to Questions......Page 996
Solutions to Exercises......Page 997
Answers to Questions......Page 1001
H: Bibliography......Page 1004
The Unified Modeling Language......Page 1005
Other Topics......Page 1006
A......Page 1008
B......Page 1011
C......Page 1012
D......Page 1016
E......Page 1018
F......Page 1019
H......Page 1022
I-J......Page 1023
K......Page 1024
M......Page 1025
O......Page 1028
P-Q......Page 1030
R......Page 1032
S......Page 1033
T......Page 1036
V......Page 1037
W-Z......Page 1038

Citation preview

Object-Oriented Programming in C++, Fourth Edition Robert Lafore

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

Copyright © 2002 by Sams Publishing

EXECUTIVE EDITOR

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.

Michael Stephens

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

Christina Smith

Library of Congress Catalog Card Number: 2001094813

INDEXER

Printed in the United States of America

Rebecca Salerno

First Printing: December 2001

PROOFREADER

Seventh Printing with corrections: February 2005

Matt Wynalda

08

TECHNICAL EDITOR

07

06

13

12

11

10

9

8

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

ACQUISITIONS EDITOR Michael Stephens

MANAGING EDITOR Matt Purcell

PROJECT EDITORS Angela Boley

Mark Cashman

TEAM COORDINATOR Pamalee Nelson

MEDIA DEVELOPER Dan Scherf

Warning and Disclaimer

INTERIOR DESIGNER

Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

Gary Adair

COVER DESIGNER Alan Clements

PAGE LAYOUT Ayanna Lacey

Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419 [email protected] For sales outside of the U.S., please contact International Sales [email protected]

Overview Introduction

1

1

The Big Picture

9

2

C++ Programming Basics

3

Loops and Decisions

4

Structures 131

5

Functions

6

Objects and Classes

7

Arrays and Strings

8

Operator Overloading

9

Inheritance

29

75

161 215 263 319

371

10

Pointers 429

11

Virtual Functions

503

12

Streams and Files

567

13

Multifile Programs

14

Templates and Exceptions

15

The Standard Template Library

16

Object-Oriented Software Development 801

A

ASCII Chart 849

B

C++ Precedence Table and Keywords

C

Microsoft Visual C++

D

Borland C++Builder

E

Console Graphics Lite

F

STL Algorithms and Member Functions

G

Answers to Questions and Exercises

H

Bibliography Index 981

977

633 681 725

859

863 871 881

913

895

Contents Introduction

1

1

The Big Picture 9 Why Do We Need Object-Oriented Programming? ..............................10 Procedural Languages ......................................................................10 The Object-Oriented Approach ........................................................13 Characteristics of Object-Oriented Languages......................................16 Objects ..............................................................................................16 Classes ..............................................................................................18 Inheritance ........................................................................................18 Reusability ........................................................................................21 Creating New Data Types ................................................................21 Polymorphism and Overloading ......................................................21 C++ and C..............................................................................................22 Laying the Groundwork ........................................................................23 The Unified Modeling Language (UML)..............................................23 Summary ................................................................................................25 Questions................................................................................................25

2

C++ Programming Basics 29 Getting Started ......................................................................................30 Basic Program Construction ..................................................................30 Functions ..........................................................................................31 Program Statements..........................................................................32 Whitespace........................................................................................33 Output Using cout ................................................................................33 String Constants................................................................................34 Directives ..............................................................................................35 Preprocessor Directives ....................................................................35 Header Files......................................................................................35 The using Directive..........................................................................36 Comments ..............................................................................................36 Comment Syntax ..............................................................................36 When to Use Comments ..................................................................37 Alternative Comment Syntax ..........................................................37 Integer Variables ....................................................................................38 Defining Integer Variables................................................................38 Declarations and Definitions ............................................................40 Variable Names ................................................................................40 Assignment Statements ....................................................................40

Integer Constants ..............................................................................41 Output Variations ..............................................................................41 The endl Manipulator ......................................................................41 Other Integer Types ..........................................................................42 Character Variables ................................................................................42 Character Constants..........................................................................43 Initialization......................................................................................44 Escape Sequences ............................................................................44 Input with cin ........................................................................................45 Variables Defined at Point of Use ....................................................47 Cascading dimensions; cout > grade; } void showtype() const //display type { cout