C++ Weekend Crash Course Contents
C++ Weekend Crash Course Contents
C++ Weekend
Crash Course
Stephen R. Davis
John Kilcullen
Chairman and CEO
IDG Books Worldwide, Inc.
IDG is the world’s leading IT media, research and exposition company. Founded in 1964, IDG had 1997 revenues of $2.05
billion and has more than 9,000 employees worldwide. IDG offers the widest range of media options that reach IT buyers
in 75 countries representing 95% of worldwide IT spending. IDG’s diverse product and services portfolio spans six key areas
including print publishing, online publishing, expositions and conferences, market research, education and training, and
global marketing services. More than 90 million people read one or more of IDG’s 290 magazines and newspapers, including
IDG’s leading global brands — Computerworld, PC World, Network World, Macworld and the Channel World family of
publications. IDG Books Worldwide is one of the fastest-growing computer book publishers in the world, with more than
700 titles in 36 languages. The “...For Dummies®” series alone has more than 50 million copies in print. IDG offers online
users the largest network of technology-specific Web sites around the world through IDG.net (http://www.idg.net), which
comprises more than 225 targeted Web sites in 55 countries worldwide. International Data Corporation (IDC) is the world’s
largest provider of information technology data, analysis and consulting, with research centers in over 41 countries and more
than 400 research analysts worldwide. IDG World Expo is a leading producer of more than 168 globally branded conferences
and expositions in 35 countries including E3 (Electronic Entertainment Expo), Macworld Expo, ComNet, Windows World
Expo, ICE (Internet Commerce Expo), Agenda, DEMO, and Spotlight. IDG’s training subsidiary, ExecuTrain, is the world’s
largest computer training company, with more than 230 locations worldwide and 785 training courses. IDG Marketing
Services helps industry-leading IT companies build international brand recognition by developing global integrated marketing
programs via IDG’s print, online and exposition products worldwide. Further information about the company can be found
at www.idg.com. 1/26/00
4689-9 FM.f.qc 3/7/00 9:17 PM Page vi
Credits
Acquisitions Editor Graphics and Production Specialists
Greg Croy Robert Bihlmayer
Jude Levinson
Project Editor
Michael Lewis
Matthew E. Lusher
Ramses Ramirez
Technical Editor Victor Pérez-Varela
Greg L. Guntle Dina F Quan
Copy Editors Quality Control Specialist
S.B. Kleinman Laura Taflinger
Rich Adin
Proofreading and Indexing
Media Development Specialist York Production Services
Jason Lusher
Illustrators
Permissions Editor Mary Jo Richards
Lenora Chin Sell Brent Savage
Media Development Manager Cover Design
Stephen Noetzel Clark Creative Group
Project Coordinators
Linda Marousek
Louigene A. Santos
Marcos Vergara
Preface
C
++ Weekend Crash Course teaches the reader C++ in one admittedly busy
weekend: 30 sessions of a half-hour each, for 15 hours stretching from
Friday evening to Sunday afternoon. At the end of each part of the book,
you’ll get a chance to pause, reflect, and review what you’ve just learned before
pushing on through the rest. Good luck!
What is C++?
C++ is the most popular programming language in use today. C++ is used in appli-
cations from the micro-programs that drive your microwave oven, your clothes
washer and your TV up through the huge, hardcore programs that control nuclear
missiles and Mars rockets — heh, you can’t blame the Mars rockets on C++.
In the late 1980s C began to show signs of age. For one, C does not support the
object-oriented programming style. At the time, the object-oriented wave was tak-
ing the world by storm. Employers were throwing money at object-oriented pro-
grammers. All you had to do was work the phrase “new paradigm” into the
conversation in order to gather a crowd of admirers.
The problem was that every program worth its salt was written in C (there were
a few programs written in Pascal like early versions of Windows, but they don’t
count — if you are familiar with the earliest versions of Windows, you know why).
There was no way that companies were going to rewrite all that code just to ride
the object-oriented wave.
Object-oriented concepts had to be grafted onto the existing C language. The
result was called C++.
4689-9 FM.f.qc 3/7/00 9:17 PM Page x
x Preface
C++ is a superset of C. Any well written C program can be rebuilt with a C++
tool to generate a working program. That meant the companies could upgrade
their software in pieces. Existing code could remain in C while new code adopted
the extra features of C++.
Fortunately for us, C++ is a standardized language. The American National
Standards Institute (ANSI) and International Standards Organization (ISO) agree
on what C++ is. They issued a detailed description of the C++ language. This
standardized language is often known as ANSI or ISO standard C++ or simply
Standard C++.
Standard C++ is not controlled by a single company such as Microsoft (or Sun,
for that matter). The Standard C++ community is not held hostage to the whims
of any one corporate giant. In addition, companies do not stray. Even Microsoft’s
Visual C++ holds tightly to the C++ standard.
The programs in C++ Weekend Crash Course in can be built using any Standard
C++ implementation.
Who
C++ Weekend Crash Course is intended for the beginner through the intermediate
reader.
This book serves the beginner by not assuming any knowledge of programming
or programming concepts. The first few lessons go over real-world, non-techie
explanations of what programming is.
This book is also great for the home programmer. The multiple examples demon-
strate programming techniques used in modern, high speed programs.
4689-9 FM.f.qc 3/7/00 9:17 PM Page xi
Preface xi
What
C++ Weekend Crash Course is more than just a book: it’s a complete development
package. A CD-ROM containing the famous GNU C++ environment is included with
the book.
You need a word processor, such as Microsoft Word, in order to do word processing.
Similarly, you need a C++ development environment in order to build and execute
programs in C++.
Many readers will already own a programming environment such as Microsoft’s
ubiquitous Visual C++. For those who do not own a C++ environment already, C++
Weekend Crash Course includes the standard GNU C++.
GNU C++ is not some stripped down, limited time program. The GNU C++ pack-
age included with the book is a complete, no-holds-barred development environ-
ment. C++ Weekend Crash Course provides complete instructions on how to install
and use both GNU C++ and Visual C++.
How
C++ Weekend Crash Course follows a one-weekend format. Start with Friday
evening; conclude Sunday afternoon.
This “One weekend” format is:
ideal for the student who wants to catch up with the rest of the class,
ideal for the one-time programmer who wants to brush up on his skills, and
ideal for anyone who wants to learn C++ while the kids are off at
Grandma’s house.
Of course, you can proceed through the book at a more leisurely pace, if you
prefer. Each section of 4 to 6 lessons can be read independently.
The reader should be able to complete each of 30 sessions in 30 minutes. Time
markers in the lesson margin help keep the reader on pace.
Each session is followed by a set of review questions to allow the reader to judge
her comprehension of the material. A set of more involved problems is provided at the
end of each part to help drive home knowledge gained during the weekend session.
4689-9 FM.f.qc 3/7/00 9:17 PM Page xii
xii Preface
Overview
C++ Weekend Crash Course presents its sessions in groups of 4 to 6 chapters,
organized into 6 parts:
This part introduces programming concepts and progresses you through your
first program.
This part covers beginning topics such as statement syntax, operators and basic
function.
Here the reader delves the slightly more complicated topic of pointer variables
including their application in linked lists, arrays and objects.
This is the jumping-off point — topics such as C++ structures, which form the basis
for object-oriented programming are discussed.
Here it is — the mother lode. This part delves into both the syntax and the mean-
ing of object-oriented programming.
This part wraps up some of the more involved topics such as error handling using
exceptions and overloading operators.
4689-9 FM.f.qc 3/7/00 9:17 PM Page xiii
Preface xiii
Each part ends with a discussion of debugging techniques for finding and
removing the inevitable errors from your programs. The level of complexity of
these techniques is chosen to match the reader’s ability glean from that session.
The appendix includes more involved programming problems for each lesson.
Note
Tip
Never
CD-ROM
4689-9 FM.f.qc 3/7/00 9:17 PM Page xiv
xiv Preface
We also occasionally highlight text passages that explain key concepts of C++
syntax, like so:
SYNTAX A function is a logically separate block of C++ code. The function construct
has the form:
What’s left?
Nothing. Open your work book to the first page and start the clock. It’s Friday
evening: you have two days.
4689-9 FM.f.qc 3/7/00 9:17 PM Page xv
Acknowledgments
W
riting a book like C++ Weekend Crash Course is a challenge, especially
since it’s one of the first titles in a new series. I’m pleased to have had
the opportunity to help launch a new way to teach readers the basics
of programming.
I’d first like to thank Greg Croy, acquisitions editor, for spearheading this new
series and selecting me as an author. I’d also like to thank my agent, Claudette
Moore, for her work with Greg and me to get this project moving.
The editorial staff at IDG Books has been very helpful, and their contributions
have made this a better book: Matt Lusher, project editor; S.B. Kleinman and Rich
Adin, copy editors; and the production staff directly responsible for the look of
what you now hold in your hands. Greg Guntle, technical editor, provided a sharp
eye for accuracy and detail.
Finally, and most of all, I’d like to thank my family, whose support of my writ-
ing makes it all worthwhile.
4689-9 FM.f.qc 3/7/00 9:17 PM Page xvi
e
ng
tter
fol-
its
4689-9 FM.f.qc 3/7/00 9:17 PM Page xvii
xvii
Contents at a Glance
Preface .......................................................................................................ix
Acknowledgments .......................................................................................xv
FRIDAY ....................................................................................2
Part I—Friday Evening ..............................................................4
Session 1–What Is Programming Anyway? ........................................................5
Session 2–Creating Your First C++ Program in Visual C++ ..................................11
Session 3–Creating Your First C++ Program in GNU C++ .....................................23
Session 4–C++ Instructions ...........................................................................37
Part I—Friday Evening Review .......................................................................45
SATURDAY ...............................................................................48
Part II—Saturday Morning .......................................................50
Session 5–Variable Types ..............................................................................51
Session 6–Mathematical Operations ...............................................................65
Session 7–Logical Operations ........................................................................73
Session 8–Flow Control Commands .................................................................85
Session 9–Functions ...................................................................................101
Session 10–Debugging I ..............................................................................115
Part II—Saturday Morning Review ................................................................127
o
SUNDAY ................................................................................298
r,
Part V—Sunday Morning ........................................................300
Session 21–Inheritance ..............................................................................301
Session 22–Polymorphism ...........................................................................315
Session 23–Abstract Classes and Factoring ....................................................329
Session 24–Multiple Inheritance ..................................................................345
Session 25–Large Programs .........................................................................361
Session 26–C++ Preprocessor .......................................................................373
Part V—Sunday Morning Review ...................................................................384
Appendix A ...............................................................................................461
Appendix B ...............................................................................................483
Appendix C ...............................................................................................497
Index .......................................................................................................501
End-User License Agreement ......................................................................514
GNU General Public License........................................................................517
CD-ROM Installation Instructions ................................................................526
4689-9 FM.f.qc 3/7/00 9:17 PM Page xix
Contents
Preface .......................................................................................................ix
Acknowledgments .......................................................................................xv
FRIDAY .....................................................................................2
Part I–Friday Evening ................................................................4
Friday Evening ..........................................................................4
Session 1–What Is Programming Anyway? ......................................................5
A Human Program ...........................................................................................6
The algorithm ..............................................................................................6
The processor ...............................................................................................7
The program ................................................................................................7
Computer processors .....................................................................................9
Session 2–Creating Your First C++ Program in Visual C++ ...............................11
Installing Visual C++ .....................................................................................12
Creating Your First Program ...........................................................................12
Building Your Program ..................................................................................14
Executing Your Program ................................................................................18
Closing Points ...............................................................................................20
Program output ..........................................................................................20
Visual C++ help ...........................................................................................20
Session 3–Creating Your First C++ Program in GNU C++ .................................23
Installing GNU C++ ........................................................................................24
Creating Your First Program ...........................................................................26
Entering the C++ code .................................................................................26
Building Your Program ..................................................................................29
Executing Your Program ................................................................................33
Closing Points ...............................................................................................34
Program output ..........................................................................................35
GNU C++ help .............................................................................................35
Session 4–C++ Instructions .........................................................................37
The Program .................................................................................................37
The C++ Program Explained ...........................................................................39
The basic program framework .......................................................................39
Comments ..................................................................................................40
There’s that framework again ........................................................................40
Statements .................................................................................................41
Declarations ...............................................................................................41
Input/output .............................................................................................42
4689-9 FM.f.qc 3/7/00 9:17 PM Page xx
xx Content
Expressions ...................................................................................................42
Assignment ................................................................................................43
Expressions (continued) ...............................................................................43
Part I–Friday Evening Review .........................................................................45
SATURDAY ...............................................................................48
Part II–Saturday Morning .........................................................50
Session 5–Variable Types ............................................................................51
Decimal Numbers ..........................................................................................52
The limitations of int’s in C++ .......................................................................52
Solving the truncation problem ....................................................................55
Limitations of floating point ........................................................................56
Other Variable Types .....................................................................................57
Types of constants ......................................................................................59
Special characters .......................................................................................59
Mixed Mode Expressions ................................................................................61
Session 6–Mathematical Operations .............................................................65
Arithmetic Operators .....................................................................................66
Expressions ...................................................................................................67
Operator Precedence ......................................................................................68
Unary Operators ............................................................................................69
Assignment Operators ...................................................................................71
Session 7–Logical Operations ......................................................................73
Simple Logical Operators ...............................................................................74
Short circuits and C++ .................................................................................76
Logical variable types ..................................................................................76
Binary Numbers ............................................................................................77
Bitwise Logical Operations .............................................................................78
The single-bit operators ...............................................................................78
The bitwise operators ..................................................................................80
A simple test ..............................................................................................81
Why? .........................................................................................................82
Session 8–Flow Control Commands ...............................................................85
The Branch Command ....................................................................................86
Looping Commands .......................................................................................87
The while loop ............................................................................................88
The for loop ...............................................................................................91
Special loop controls ...................................................................................93
Nested Control Commands .............................................................................96
Can We switch to a Different Subject? ............................................................97
4689-9 FM.f.qc 3/7/00 9:17 PM Page xxi
Contents xxi
xxii Content
Contents xxiii
xxiv Content
Exercises .....................................................................................................293
Problems ..................................................................................................293
Hint ........................................................................................................294
My solution ..............................................................................................294
Part IV–Saturday Evening Review..................................................................296
SUNDAY ................................................................................298
Part V–Sunday Morning ..........................................................300
Session 21–Inheritance ............................................................................301
Advantages of Inheritance ...........................................................................302
Class Factoring ............................................................................................303
Implementing Inheritance in C++ ................................................................303
Constructing a Subclass ...............................................................................308
The HAS_A Relationship ..............................................................................311
Session 22–Polymorphism .........................................................................315
Overriding Member Functions ......................................................................316
Enter Polymorphism ....................................................................................318
Polymorphism and Object-Oriented Programming .........................................320
How Does Polymorphism Work? ...................................................................322
When Is a Virtual Function Not? ..................................................................324
Virtual Considerations .................................................................................326
Session 23–Abstract Classes and Factoring .................................................329
Factoring .....................................................................................................329
Abstract Classes ...........................................................................................334
Declaring an abstract class .........................................................................335
Making a “concrete” class out of an abstract class .........................................337
When is a subclass abstract? .......................................................................339
Passing an abstract object to a function .......................................................341
Why are pure virtual functions needed? .......................................................342
Session 24–Multiple Inheritance ...............................................................345
How Does Multiple Inheritance Work? ..........................................................346
Inheritance Ambiguities ..............................................................................348
Virtual Inheritance ......................................................................................349
Constructing the Objects of Multiple Inheritance ..........................................356
A Contrary Opinion ......................................................................................357
Session 25–Large Programs .......................................................................361
Why Divide Programs? .................................................................................361
Separating Class Definition from Application Program ..................................362
Dividing the program .................................................................................362
The #include directive ................................................................................364
Dividing application code ...........................................................................365
Project file ...............................................................................................367
Reexamining the standard program template ................................................370
Handling outline member functions .............................................................371
4689-9 FM.f.qc 3/7/00 9:17 PM Page xxv
Contents xxv
xxvi Content