Tải bản đầy đủ (.pdf) (1,029 trang)

Object oriented programming in c++r

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.21 MB, 1,029 trang )

This document is created with a trial version of CHM2PDF Pilot


Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98

Previous Table of Contents Next

Introduction
Object-Oriented Programming (OOP) is the most dramatic innovation in software development in
the last decade. It ranks in importance with the development of the first higher-level languages at
the dawn of the computer age. Sooner or later, every programmer will be affected by the objectoriented approach to program design.

Advantages of OOP
Why is everyone so excited about OOP? The chief problem with computer programs is complexity.
Large programs are probably the most complicated entities ever created by humans. Because of this
complexity, programs are prone to error, and software errors can be expensive and even life
threatening (in air-traffic control, for example). Object-Oriented Programming offers a new and
powerful way to cope with this complexity. Its goal is clearer, more reliable, more easily
maintained programs.

Languages and Development Platforms
Of the Object-Oriented Programming languages, C++ is by far the most widely used. (Java, a recent
addition to the field of OO languages, lacks certain features, such as pointers, that make it less
powerful and versatile than C++.)
In past years the standards for C++ have been in a state of evolution. This meant that each compiler
vendor handled certain details differently. However, in November 1997, the ANSI/ISO C++
standards committee approved the final draft of what is now known as Standard C++. (ANSI stands


for American National Standards Institute, and ISO stands for International Standards Institute.)
Standard C++ adds many new features to the language, such as the Standard Template Library
(STL). In this book we follow Standard C++ (except for a few places which we’ll note as we go
along).
The most popular development environments for C++ are manufactured by Microsoft and Borland
and run on the various flavors of Microsoft Windows. In this book we’ve attempted in ensure that
all example programs run on the current versions of both Borland and Microsoft compilers. (See
Appendixes C and D for more on these compilers.)

What this Book Does


This document is created with a trial version of CHM2PDF Pilot


This book teaches Object-Oriented Programming with the C++ programming language, using either
Microsoft or Borland compilers. It is suitable for professional programmers, students, and kitchentable enthusiasts.

New Concepts
OOP 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 of ObjectOriented Programming. But it’s easy to lose sight of these concepts when discussing the specifics
of an object-oriented language. Many books overwhelm the reader with the details of language
features, while ignoring the reason these features exist. This book attempts to keep an eye on the
big picture and relate the details to the larger concepts.

The Gradual Approach
We take a gradual approach in this book, starting with very simple programming examples and
working up to full-fledged object-oriented applications. We introduce new concepts slowly so that
you will have time to digest one idea before going on to the next. We use figures whenever possible
to help clarify new ideas. There are questions and programming exercises at the end of most

chapters to enhance the book’s usefulness in the classroom. Answers to the questions and to the
first few (starred) exercises can be found in Appendix D. The exercises vary in difficulty to pose a
variety of challenges for the student.

What You Need to Know to Use this Book
You can use this book even if you have no previous programming experience. However, such
experience, in BASIC or Pascal, for example, certainly won’t hurt.
You do not need to know the C language to use this book. Many books on C++ assume that you
already know C, but this one does not. It teaches C++ from the ground up. If you do know C, it
won’t 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
applications and copying files.

Software and Hardware
You should have the latest version of either the Microsoft or the Borland C++ compiler. Both
products come in low-priced “Learning Editions” suitable for students.
Appendix C provides detailed information on operating the Microsoft compiler, while Appendix D
does the same for the Inprise (Borland) product. Other compilers will probably handle most of the
programs in this book as written, if they adhere to Standard C++.
Your computer should have enough processor speed, memory, and hard disk space to run the
compiler you’ve chosen. You can check the manufacturer’s specifications to determine these
requirements.

Console-Mode Programs


This document is created with a trial version of CHM2PDF Pilot


The example programs in this book are console-mode programs. They run in a character-mode

window within the compiler environment, or directly within an MS-DOS box. This avoids the
complexity of full-scale graphics-oriented Windows programs. Go for It!
You may have heard that C++ is difficult to learn. It’s true that it might be a little more challenging
than BASIC, but it’s really quite similar to other languages, with two or three “grand ideas” thrown
in. These new ideas are fascinating in themselves, and we think you’ll have fun learning about
them. They are also becoming part of the programming culture; they’re something everyone should
know a little bit about, like evolution and psychoanalysis. We hope this book will help you enjoy
learning about these new ideas, at the same time that it teaches you the details of programming in
C++.

A Note to Teachers
Teachers, and others who already know C, may be interested in some details of the approach we
use in this book and how it’s organized.

Standard C++
We’ve revised all the programs in this book to make them compatible with Standard C++. This
involved, at a minimum, changes to header files, the addition of namespace designation, and
making return type . Many programs received more extensive modifications, including the
substitution in many places of the new class for the old C-style strings.
We devote a new chapter to the STL (Standard Template Library), which is now included in
Standard C++.

Object-Oriented Design
Students are frequently mystified by the process of breaking a programming project into
appropriate classes. For this reason we’ve added a chapter on object-oriented design. This chapter is
placed near the end of the book, but we encourage students to skim it earlier to get the flavor of
OOD. Of course, small programs don’t require such a formal design approach, but it’s helpful to
know what’s involved even when designing programs in your head. C++ is not the same as C.
Some institutions want their students to learn C before learning C++. In our view this is a mistake.
C and C++ are entirely separate languages. It’s true that their syntax is similar, and C is actually a

subset of C++. But the similarity is largely a historical accident. In fact, the basic approach 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 we don’t
believe it is necessary or advantageous to teach C before teaching C++. Students who don’t know C
are saved the time and trouble of learning C and then learning C++, an inefficient approach.
Students who already know C may be able to skim parts of some chapters, but they will find that a
remarkable percentage of the material is new.

Optimize Organization for OOP
We could have begun the book by teaching the procedural concepts common to C and C++, and


This document is created with a trial version of CHM2PDF Pilot


We 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. That seemed
counterproductive, however, because one of our goals is to begin true Object-Oriented
Programming as quickly as possible. Accordingly, we provide a minimum of procedural
groundwork before getting to objects in Chapter 7. Even the initial chapters are heavily steeped in
C++, as opposed to C, usage.
We introduce some concepts earlier than is traditional in books on C. For example, structures are a
key feature for understanding C++ because classes are syntactically an extension of structures. For
this reason, we introduce structures in Chapter 5 so that they will be familiar when we discuss
classes.
Some concepts, such as pointers, are introduced later than in traditional C books. It’s not necessary
to understand pointers to follow the essentials of OOP, and pointers are usually a stumbling block
for C and C++ students. Therefore, we defer a discussion of pointers until the main concepts of
OOP have been thoroughly digested.


Substitute Superior C++ Features
Some features of C have been superseded by new approaches in C++. For instance, the and
functions, input/output workhorses in C, are seldom used in C++ because and do a better job.
Consequently, we leave out descriptions of these functions. Similarly, constants and macros in C
have been largely superseded by the qualifier and inline functions in C++, and need be mentioned
only briefly.

Minimize Irrelevant Capabilities
Because the focus in this book is on Object-Oriented Programming, we can leave out some features
of C that are seldom used and are not particularly relevant to OOP. For instance, it isn’t necessary
to understand the C bit-wise operators (used to operate on individual bits) to learn Object-Oriented
Programming. These and a few other features can be dropped from our discussion, 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 but briskly
toward an understanding of new concepts and their application to real programming problems.

Programming Examples
There are numerous listings of code scattered throughout the book that you will want to try out for
yourself. The program examples are available for download by going to Macmillan Computer
Publishing’s web site, and go to this book’s page by
entering the ISBN and clicking Search. To download the programming examples, just click the
appropriate link on the page.

Programming Exercises
One of the major changes in the second edition was the addition of numerous exercises. Each of
these involves the creation of a complete C++ program. There are roughly 12 exercises per chapter.


This document is created with a trial version of CHM2PDF Pilot



these involves the creation of a complete C++ program. There are roughly 12 exercises per chapter.
Solutions to the first three or four exercises in each chapter are provided in Appendix D. For the
remainder of the exercises, readers are on their own, although qualified instructors can suggested
solutions. Please visit Macmillan Computer Publishing’s Web site,
and go to this book’s page by entering the ISBN and
clicking Search. Click on the appropriate link to receive instructions on downloading the encrypted
files and decoding them.
The exercises vary considerably in their degree of difficulty. In each chapter the early exercises are
fairly easy, while later ones are more challenging. Instructors will probably want to assign only
those exercises suited to the level of a particular class.

Previous Table of Contents Next


This document is created with a trial version of CHM2PDF Pilot


Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98

Previous Table of Contents Next

Preface
The major changes to this Third Edition are concerned with Standard C++ and object-oriented
design. In addition, the book is no longer geared exclusively to Borland C++ compilers.
Standard C++, finalized in the fall of 1997, introduced many new features to C++. Some of these

features, such as templates and exceptions, had already been adopted by compiler manufacturers.
However, the Standard Template Library (STL) has only recently been included in compilers. This
book adds a chapter on the STL.
We’ve also introduced other features from Standard C++, including new header files, the string class,
new-style casts, namespaces, and so on.
The design of object-oriented programs has received increasing emphasis in recent years, so we’ve
added a chapter on object-oriented design.
The advent of Standard C++ means that, at least to a greater extent than before, all compilers should
treat source code in the same way. Accordingly, we’ve modified our emphasis on Borland
compilers, and now focus on code that should work with any Standard C++ compiler. Of course, the
reality seldom matches the ideal, so so the programs in this book have been tested with both
Microsoft and Borland compilers, and modified when necessary to work with both of them.

Previous Table of Contents Next


This document is created with a trial version of CHM2PDF Pilot


Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98

Previous Table of Contents Next

About the Author
Robert Lafore has been writing books about computer programming since 1982. His best-selling
titles include Assembly Language Programming for the IBM PC, C Programming Using Turbo

C++, C++ Interactive Course, and Data Structures and Algorithms in Java. Mr. Lafore holds
degrees in mathematics and electrical engineering, and has been active in programming since the
days of the PDP-5, when 4K of main memory was considered luxurious. His interests include
hiking, windsurfing, and recreational mathematics.

Acknowledgments to the Third Edition
I’d like to thank the entire team at Macmillan Computer Publishing. In particular, Tracy
Dunkelberger ably spearheaded the entire project and exhibited great patience with what turned out
to be a lengthy schedule. Jeff Durham handled the myriad details involved in interfacing between
me and the editors with skill and good humor. Andrei Kossorouko lent his expertise in C++ to
ensure that I didn’t make this edition worse instead of better.

Acknowledgments to the Second Edition
My thanks to the following professor—susers of this book as a text at their respective colleges and
universities—for their help in planning the second edition: Dave Bridges, Frank Cioch, Jack
Davidson, Terrence Fries, Jimmie Hattemer, Jack Van Luik, Kieran Mathieson, Bill McCarty,
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 and
suggestions, many of which were invaluable.
At Waite Group Press, Joanne Miller has ably ridden herd on my errant scheduling and filled in as
academic liaison, and Scott Calamar, as always, has made sure that everyone knew what they were
doing. Deirdre Greene provided an uncannily sharp eye as copy editor.
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
experimenting with the new exercises.

Acknowledgments to the First Edition


This document is created with a trial version of CHM2PDF Pilot



My primary thanks go to Mitch Waite, who poured over every inch of the manuscript with
painstaking 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 suitability
for classroom use, suggested many excellent improvements, and attempted to correct my dyslexic
spelling.
George Leach ran all the programs, and, to our horror, found several that didn’t perform correctly in
certain circumstances. I trust these problems have all been fixed; if not, the fault is entirely mine.
Scott Calamar of The Waite Group dealt with the myriad organizational aspects of writing and
producing this book. His competence and unfailing good humor were an important ingredient in its
completion.
I would also like to thank Nan Borreson of Borland for supplying the latest releases of the software
(among other useful tidbits), Harry Henderson for reviewing the exercises, Louise Orlando of The
Waite Group for ably shepherding the book through production, Merrill Peterson of Matrix
Productions for coordinating the most trouble-free production run I’ve ever been involved with,
Juan Vargas for the innovative design, and Frances Hasegawa for her uncanny ability to decipher
my sketches and produce beautiful and effective art.

Dedication
This book is dedicated to GGL another inodomitable spirit.222

Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator. We value your
opinion and want to know what we’re doing right, what we could do better, what areas you’d like
to see us publish in, and any other words of wisdom you’re willing to pass our way.
As the Executive Editor for the Advanced Programming and Distributed Architectures team at
Macmillan Computer Publishing, I welcome your comments. You can fax, email, or write me
directly to let me know what you did or didn’t like about this book—as well as what 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 message.
When you write, please be sure to include this book’s title and author as well as your name and
phone or fax number. I will carefully review your comments and share them with the author and
editors who worked on the book.
Fax: 317-817-7070
Email:
Mail: Tracy Dunkelberger
Executive Editor
Advanced Programming and Distributed Architectures
Macmillan Computer Publishing


This document is created with a trial version of CHM2PDF Pilot


201 West 103rd Street
Indianapolis, IN 46290 USA

Previous Table of Contents Next


This document is created with a trial version of CHM2PDF Pilot


Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98


Previous Table of Contents Next

APPENDIX A
ASCII Chart
Table A.1 IBM Character Codes
DEC
HEX
Symbol
0
00
(NULL)
A
1
01
B
2
02
C
3
03
D
4
04
E
5
05
F
6
06

G
7
07
H
8
08
I
9
09
J
10
0A
K
11
0B
L
12
0C
M
13
0D
N
14
0E
O
15
0F
P
16
10

Q
17
11
R
18
12
S
19
13
T
20
14
U
21
15
_
22
16
W
23
17
X
24
18
Y
25
19
Z
26
1A

a
27
1B
b
28
1C

Key
Ctrl 2
Ctr A
Ctrl B
Ctrl C
Ctrl B
Ctrl E
Ctrl F
Ctrl G
Backspace
Tab
Ctrl J
Ctrl K
Ctrl L
Enter
Ctrl N
Ctrl O
Ctrl P
Ctrl Q
Ctrl R
Ctrl S
Ctrl T
Ctrl U

Ctrl V
Ctrl W
Ctrl X
Ctrl Y
Ctrl Z
Escape
Ctrl \

Use in C

Beep
Backspace
Tab
Linefeed (new line)
Vertical Tab
Form Feed
Carriage Return


This document is created with a trial version of CHM2PDF Pilot


29
30
31
32
33
34
35
36

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

67
68
69
70
71
72
73

1D
1E
1F
20
21
22
23
24
25
26
27
28
29
2A
2B
2C
2D
2E
2F
30
31
32

33
34
35
36
37
38
39
3A
3B
3C
3D
3E
3F
40
41
42
43
44
45
46
47
48
49

c
d
e

!


#
$
%
&

(
)
*
+
,

.
/
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?
@

A
B
C
D
E
F
G
H
I

Ctrl ]
Ctrl 6
Ctrl –
SPACE BAR
!

#
$
%
&

(
)
*
+
,

.
/
0

1
2
3
4
5
6
7
8
9
:
;
<
=
>
?
@
A
B
C
D
E
F
G
H
I


This document is created with a trial version of CHM2PDF Pilot



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

4A
4B
4C
4D
4E
4F
50
51
52
53
54
55
56
57

58
59
5A
5B
5C
5D
5E
5F
60
61
62
63
64
65
66
67
68
69
6A
6B
6C
6D
6E
6F
70
71
72
73
74
75

76

J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
[
\
]
^
_
'
a
b
c
d
e

f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v

J
K
L
M
N
O
P
Q
R
S
T
U

V
W
X
Y
Z
[
\
]
^
_
'
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s

t
u
v


This document is created with a trial version of CHM2PDF Pilot


119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

77
78
79
7A
7B
7C

7D
7E
7F
80
81
82
83
84
85
86
87
88
89
8A
8B
8C
8D
8E
8F
90
91
92
93
94
95
96
97
98
99
9A

9B
9C
9D
9E
9F
A0
A1
A2
A3

w
x
y
z
{
|
}
~
f












ù









ũ




ĩ

Ê
Ơ




ú


w
x
y
z

{
|
}
~
Ctrl
Alt 128
Alt 129
Alt 130
Alt 131
Alt 132
Alt 133
Alt 134
Alt 135
Alt 136
Alt 137
Alt 138
Alt 139
Alt 140
Alt 141
Alt 142
Alt 143
Alt 144
Alt 145
Alt 146
Alt 147
Alt 148
Alt 149
Alt 150
Alt 151
Alt 152

Alt 153
Alt 154
Alt 155
Alt156
Alt157
Alt158
Alt159
Alt160
Alt161
Alt162
Alt163


This document is created with a trial version of CHM2PDF Pilot


164
165
166
167
168
169
170
171
172
173
174
175
176
177

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207

208

A4
A5
A6
A7
A8
A9
AA
AB
AC
AD
AE
AF
B0
B1
B2
B3
B4
B5
B6
B7
B8
B9
BA
BB
BC
BD
BE
BF

C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
D0

ñ
Ñ
a
o
®
©

'
..
¡
«
»

¤
¤
¤

¥
µ
ð
ς
Π
π

a
o
Ω
æ

¿
¡
¬



Δ
«
»
...
g
À
Ã
Õ

Œ
œ


Alt164
Alt165
Alt166
Alt167
Alt168
Alt169
Alt170
Alt 171
Alt 172
Alt 173
Alt 174
Alt 175
Alt 176
Alt 177
Alt 178
Alt 179
Alt 180
Alt 181
Alt 182
Alt 183
Alt 184
Alt 185
Alt 186
Alt 187
Alt 188
Alt 189

Alt 190
Alt 191
Alt 192
Alt 193
Alt 194
Alt 195
Alt 196
Alt 197
Alt 198
Alt 199
Alt 200
Alt 201
Alt 202
Alt 203
Alt 204
Alt 205
Alt 206
Alt 207
Alt 208


This document is created with a trial version of CHM2PDF Pilot


209
210
211
212
213
214

215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

245
246
247
248
249
250
251
252
253

D1
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF
E0
E1
E2
E3
E4

E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD


"
"
Ô

"
÷

ÿ
Ÿ
/
¤
<
>
fi
fl
α
β
Γ
π
ς
Â
µ
τ
Ë
Θ
Ω
Î
Ï
ψ


Ô

+



Ù
1

÷


°

.

η
²

Alt 209
Alt 210
Alt 211
Alt 212
Alt 213
Alt 214
Alt 215
Alt 216
Alt 217
Alt 218
Alt 219
Alt 220
Alt 221
Alt 222
Alt 223

Alt 224
Alt 225
Alt 226
Alt 227
Alt 228
Alt 229
Alt 230
Alt 231
Alt 232
Alt 233
Alt 234
Alt 235
Alt 236
Alt 237
Alt 238
Alt 239
Alt 240
Alt 241
Alt 242
Alt 243
Alt 244
Alt 245
Alt 246
Alt 247
Alt 248
Alt 249
Alt 250
Alt 251
Alt 252
Alt 253



This document is created with a trial version of CHM2PDF Pilot


254
255

FE
FF

<
(blank)

Alt 254
Alt 255

Those key sequences consisting of “Ctrl” are typed by pressing the CTRL key, and while it is being
held down, pressing the key indicated. These sequences are based on those defined for PC Personal
Computer series keyboards. The key sequences may be defined differently on other keyboards.
IBM Extended ASCII characters can be displayed by pressing the Alt key and then typing the
decimal code of the character on the keypad.

Previous Table of Contents Next


This document is created with a trial version of CHM2PDF Pilot


Waite Group's Object-Oriented Programming in C++, Third Edition

(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98

Previous Table of Contents Next

APPENDIX B
STANDARD C++ KEYWORDS
Keywords implement specific C++ language features. They cannot be used as names for variables
or other user-defined program elements. Many of the keywords are common to both C and C++,
while others are specific to C++. Some compilers may support additional keywords, which usually
begin with one or two underscores, as in _cdecl or __int16.

A
asm
auto

B
bool
break

C
case
catch
char
class
const
const_cast
continue


D
default
delete
do
double
dynamic_cast

E
else


This document is created with a trial version of CHM2PDF Pilot


enum
explicit
export
extern

F
false
float
for
friend

G
goto

I

if
inline
int

L
long

M
main
mutable

N
namespace
new

O
operator

P
private
protected
public

R
register
reinterpret_cast
return


This document is created with a trial version of CHM2PDF Pilot



S
short
signed
sizeof
static
static_cast
struct
switch

T
template
this
throw
true
try
typedef
typeid
typename

U
union
unsigned
using

V
virtual
void
volatile


W
wchar_t
while

Previous Table of Contents Next


This document is created with a trial version of CHM2PDF Pilot


Waite Group's Object-Oriented Programming in C++, Third Edition
(Publisher: Macmillan Computer Publishing)
Author(s): Robert Lafore
ISBN: 157169160x
Publication Date: 11/25/98

Previous Table of Contents Next

APPENDIX C
MICROSOFT VISUAL C++
This appendix tells you how to use Microsoft Visual C++ to create console-mode applications,
which are the kind of applications used in this book. This discussion is based on Visual C++ version
5.0.
The present version of Visual C++ has good (although not perfect) adherence to Standard C++. It
comes in various versions, including a student version for under $100.
We’ll assume that Visual C++ is installed in your system, and that you know how to start it by using
the Windows Start button and navigating to the appropriate menu item: Microsoft Visual C++.
You’ll want to make sure you can see file extensions (like .CPP) when operating MVC++. In
Windows Explorer, make sure that the option Hide MS-DOS File Extensions for File Types That

are Registered is not checked.

Screen Elements
When you start Microsoft Visual C++ you’ll see that the resulting application is actually called
Microsoft Developer Studio. The studio can work with other languages besides C++, but we won’t
worry about that here.
The Developer Studio window is initially divided into three parts. On the left is the View Pane.
This has three tabs, for ClassView, FileView, and InfoView. Once you have a project going, the
ClassView tab will show you the class hierarchy of your program, and FileView will show you the
files used in the project. InfoView allows you to navigate through the documentation and help file
structure. Click the plus signs to expand the hierarchies, then double-click the document you want
to read.
The largest part of the screen usually holds a document window. It can be used for various
purposes, including displaying your source files. It can also display the contents of help files. At the
bottom of the screen is a long window with more tabs: Build, Debug, and so on. This will display
messages when you perform operations such as compiling your program.

Single-File Programs
It’s easy to build and execute a single-file console program using Microsoft Visual C++. There are


This document is created with a trial version of CHM2PDF Pilot


It’s easy to build and execute a single-file console program using Microsoft Visual C++. There are
two possibilities: the file already exists or the file needs to be written.
In either case you should begin by making sure that no project is currently open. (We’ll discuss
projects in a moment.) Click the File menu. If the Close Workspace item is active (not grayed) click
it to close the current workspace.


Building an Existing File
If the .CPP source file already exists, as it does for the example programs in this book, select Open
from the File menu. (Note that this is not the same as Open Workspace.) Use the Open dialog box
to navigate to the appropriate file, select it, and click the Open button. The file will appear in the
document window. (If you’re compiling an example program that uses Console Graphics Lite, such
as the CIRCSTRC program in Chapter 5, “Functions,” or the CIRCLES program in Chapter 6, “Objects
and Classes,” turn to the section “Building Console Graphics Lite Programs.”)
To compile and link this file, select Build from the Build menu. A dialog box will appear asking if
you want to create a Default Project Workspace. Click Yes. The file will be compiled and linked
with any necessary library files.
To run the program, select Execute from the Project menu. If all goes well, a console window will
appear with the program’s output displayed in it.
When the program terminates, you’ll see the phrase Press any key to continue. The compiler
arranges for this to be inserted following the termination of any program. It keeps the console
display on the screen long enough to see the program’s output.
You can also run programs directly from MS-DOS. In Windows 95 and 98, you can obtain a box
for MS-DOS by clicking the Start button, selecting Programs and then the MS-DOS Prompt item.
In the resulting window you’ll see what’s called the C-prompt: the letter C, usually followed by the
name of the current directory. You can navigate from one directory to another by typing cd (for
Change Directory) and the name of the new directory. To execute a program, including any of the
examples from this book, make sure you’re in the same directory as the appropriate .EXE file, and
type the name of the program (with no extension). You can find out more about MS-DOS using the
Windows help system.

Writing a New File
To start writing your own .CPP file, select New from the File menu and click the Files tab. Select
C++ Source File, and click OK. A blank document window will appear. Type in your program.
Save the new file by selecting Save As from the File menu, navigating to the correct directory, and
typing the file name with the .CPP extension (such as myProg.cpp). As before, select Build from the
Build menu and click Yes to the default workspace question. Your program will be compiled and

linked.
If there are errors, they will appear in the Build window at the bottom of the screen. (You may need
to click the Build tab to make this window appear.) If you double-click the error line, an arrow will
appear next to the line containing the error in the source file. Also, if you position the cursor on the
error number in the Build window (such as C2143) and press the F1 key, an explanation of the error
will appear in the document window. You can correct the errors and repeat the build process until
the message reads “0 error(s), 0 warning(s).” To execute the program, select Execute from the
Build menu.


This document is created with a trial version of CHM2PDF Pilot


Before working on a new program, don’t forget to select Close Workspace from the File menu.
This ensures that you begin with a clean workspace. To open a program you’ve already built, select
Open Workspace from File menu, navigate to the right directory, and double-click the file with the
appropriate name and the .DSW extension.

Run-Time Type Information (RTTI)
A few programs, such as EMPL_IO.CPP in Chapter 12, “Streams and Files,” use RTTI. With
Microsoft Visual C++ you need to enable a compiler option to make this feature work. Select
Settings from the Project menu and click the C/C++ tab. From the Category list box, select C++
Language. Click the checkbox named Enable Run-Time Type Information. This will avoid various
compiler and linker errors, some of which are misleading.

Multifile Programs
We’ve shown the quick and dirty approach to building programs. This approach works with onefile programs. When projects have more than one file things become slightly more complicated.
We’ll start by reviewing what’s meant by the terms workspace and project.

Projects and Workspaces

Visual C++ uses a concept called a workspace, which is one level of abstraction higher than a
project. A workspace can contain many projects. It consists of a directory and several configuration
files. Within it, each project can have its own directory, or the files for all the projects can simply
reside in the workspace directory.
Conceptually it’s probably easiest, at least for the small programs in this book, to assume that every
project has its own separate workspace. That’s what we’ll assume in this discussion.
A project corresponds to an application (program) that you’re developing. It consists of all the files
needed to create that application as well as information about how these files are to be combined.
The result of building a project is usually a single .EXE file that a user can execute. (Other results
are possible, such as .DLL files.)

Source Files Already Exist
Let’s assume that the files you want to include in a new project already exist, and that they are in a
particular directory. Select New from the File menu, and click the Projects tab in the New dialog
box. Select Win32 Console Application from the list. First, in the Location box, type the path to the
directory, but do not include the directory name itself. Next, type the name of the directory
containing the files in the Project Name box. (By clicking the button to the right of the Location
field you can navigate to the appropriate directory, but make sure to delete the directory name itself
from the location field.) Make sure the Create New Workspace box is checked, and click OK.
For example, if the files are in C:\Book\Ch13\Elev, then you would first type C:\Book\Ch13\ in the
Location field and then Elev in the Project Name field. When you type the project name, it’s
automatically added to the location. (If it was there already it would be added again, resulting in a
location of C:\Book\Ch13\Elev\Elev, which is not what you want.)


This document is created with a trial version of CHM2PDF Pilot


At this point various project-oriented files, with extension .DSP, .DSW, and so forth, have been
added to the directory.

Now you need to add your source files to the project. This includes both .CPP and .H files. Select
Add To Project from the Project menu, click Files, select the files you want to add, and click OK.
You can review the files you’ve selected by clicking the FileView tab and then the plus sign for the
project. You can also see the class structure, complete with member functions, by clicking the
ClassView tab.
To open a file so you can see it and modify it, select Open from the File menu and select the file.
Sometimes a file (such as the msoftCon.h file necessary for console graphics programs) is not in the
same directory as the other source files for your program. You can nevertheless add it to your
project in the same way that you add other files. Select Add To Project from the Project menu,
select Files, and then navigate to the file you want (or type in the complete pathname).

Saving, Closing, and Opening Projects
To save the project, select Save Workspace. To close the project, select Close Workspace. (Answer
Yes to the query Close All Document Windows.) To open an existing project, select Open
Workspace from the file menu, navigate to the proper directory, select the .DSW file, and click
Open.

Compiling and Linking
As with one-file programs, the easiest way to compile, link, and run a multifile program is to select
Execute from the Build menu. You can compile and link your project without running it by
selecting Build from the Build menu.

Building Console Graphics Lite Programs
Building programs that use the Console Graphics Lite functions (described in Appendix E,
“Console Graphics Lite”) requires some steps in addition to those needed for ordinary example
programs. Programs that use these functions should include the line #include “msoftcon.h”.

• Open the source file for the program as described earlier.
• Select Build from the Build menu. Answer Yes when asked if you want to create a default
project workspace. A project will be created, but the compiler will complain it can’t find

MSOFTCON.H.

• To tell it where to find this file, select Options from the Tools menu. Click on the
Directories tab. Select Include Files from the Show Directories For list. On the bottom line of
the Directories list, type the complete pathname of the directory where MSOFTCON.H is
stored. (This directory should be called MSOFTCON.) Click on OK.
• Now try building your file again. Now the compiler can find the header file, but there will
be numerous linker errors because the linker doesn’t know where to find the code for the
graphics functions. This code is in MSOFTCON.CPP.
• Select Add To Project from the Project menu; then select Files. In the resulting dialog box
(called Insert Files into Project), navigate to the MSOFTCON directory. Select the
MSOFTCON.CPP file. Click OK.


This document is created with a trial version of CHM2PDF Pilot


Now your program should compile and link correctly. Select Execute from the Build menu to see it
run.

Debugging
In Chapter 3, “Loops and Decisions,” we suggest using the debugger to provide an insight into how
loops work. Here’s how to do that with Microsoft Visual C++. These same steps can help you
debug your program if it behaves incorrectly. We’ll be discussing one–file programs here, but the
same approach applies, with appropriate variations, to larger multifile programs.
Start by building your program as you normally would. Fix any compiler and linker errors. Make
sure your program listing is displayed in the Edit window.

Single Stepping
To start the debugger, simply press the F10 key. You’ll see a yellow arrow appear in the margin of

the listing, pointing to the opening brace following main.
If you want to start somewhere other than the beginning of the program, position the cursor on the
line where you want to start debugging. Then, from the Build menu, select Start Debug, and then
Run to Cursor. The yellow arrow will appear next to the statement selected.
Now press the F10 key. This causes the debugger to step to the next executable statement. The
yellow arrow will show where you are. Each press of F10 moves it to the next statement. If you’re
in a loop, you’ll see the yellow arrow move down through the statements in the loop and then jump
back to the top of the loop.

Watching Variables
You’ll see a Watch window in the bottom right corner of your screen. To observe the values of
variables change as you step through the program, you’ll need to place these variable’s names in
this Watch window. To do this, right–click a variable name in the source code. A pop–up menu will
appear. Select QuickWatch from this menu. In the resulting QuickWatch dialog box, click Add
Watch. The variable and its current value will appear in the Watch window. If a variable is out of
scope, such as before it’s been defined, the Watch window will show an error message instead of a
value next to the variable name.

Stepping Into Functions
If your program uses functions, you can step into them (single–step through the statements within
the function) by using the F11 key. By contrast, the F10 key steps over function calls (treats them
as a single statement). If you use F11 to trace into library routines like cout <<, you can trace
through the source code of the library routine. This can be a lengthy process, so avoid it unless
you’re really interested. You need to switch judiciously between F11 and F10, depending on
whether you want to explore a particular function’s inner workings or not.

Breakpoints


This document is created with a trial version of CHM2PDF Pilot



Breakpoints allow you to stop the program at any arbitrary location. Why are they useful? We’ve
already shown that you can execute the program up to the cursor location by selecting Run to
Cursor. However, there are times when you want to be able to stop the program in multiple
locations. For example, you might want to stop it after an if and also after the corresponding else.
Breakpoints solve this problem because you can insert as many as you need. (They also have
advanced features we won’t describe here.)
Here’s how to insert a breakpoint in your listing. First, position the cursor on the line where you
want the breakpoint. Then click the right mouse button, and from the resulting menu select
Insert/Remove Breakpoint. You’ll see a red circle appear in the left margin. Now whenever you run
your program at full speed (by selecting Build/Start Debug/Go, for example) it will stop at the
breakpoint. You can then examine variables, single–step through the code, or run to another
breakpoint.
To remove a breakpoint, right–click it and select Remove Breakpoint from the menu.
There are many other features of the Debugger, but what we’ve discussed here will get you started.

Previous Table of Contents Next


×