|
Simply C++
Preface
Welcome
to C++! This book, the fifth in our new Simply
series, was a joy to create. The book focuses on core concepts and features
of C++ while keeping the discussions as simple as possible. 
To achieve
these goals, we present the core concepts of leading-edge computing
technologies using the tutorial-based,
Application-Driven approach, combined with the Deitel
signature Live-Code
approach of teaching programming using complete, real-world
applications.
We merged the notion of a lab manual with that of a conventional textbook,
creating a book that works well in a traditional classroom setting or with
students sitting at computers and building each example application as they
read the tutorials.
As students
work through the tutorials, they learn about C++ and its fundamental
features, control statements, functions, file processing, classes, pointers,
the C++ Standard Template Library and more. At the end of most sections, we
provide self-review questions with answers so that students receive
immediate feedback on their understanding of the material.
Features in Simply C++
This book is loaded with pedagogic
features, including:
n
Application-Driven Tutorial Approach. Each tutorial uses a
contemporary, real-world application to teach programming concepts. The
examples and exercises are up-to-the-minute with popular applications, such
as wage calculating, game playing, investing, and ticket ordering. Most
examples have a business focus. At the beginning of each tutorial, students
test-drive
the completed application so they can see how it works. Then, they build the
application by following step-by-step instructions. The book concentrates on
the principles of good software design and stresses program clarity.
n
Live-Code
Approach. This book contains many Live-Code
examples. Each tutorial ends with the complete, working application code and
the students can run the application that they just created. We call this
method of teaching and writing the
Live-Code
Approach. We feel that this approach is more effective
than presenting only code snippets out of the context of a complete
application.
n
Real-World Technologies. This text
incorporates todays
technologies to develop useful applications. For example, we use the Unified
Modeling Language (UML) to replace flowchartsan
older standard. The UML has become the preferred graphical modeling language
for designing object-oriented applications. We use the UML to show the flow
of control for several applications, so students gain practice reading the
type of diagrams that are used in industry.
n
Full-Color
Presentation. This book is in full color so that students
can see sample outputs as they might appear on a computer monitor. Also, we
syntax color the C++ code, similar to the way C++ integrated development
environments (IDEs) color the code in their editor windows. This way,
students can match what they see in the book with what they see on their
screens. Our syntax-coloring conventions are as follows:
keywords appear in dark blue
literal
values and constants appear in light blue
class, function and variable names and text
appear in black
errors appear in red
n
Object-Oriented Programming.
Object-oriented programming is the most widely employed technique for
developing robust, reusable software, and C++ offers advanced
object-oriented programming features. This book introduces students to
defining classes and using objects, and lays a solid foundation for future
programming courses.
n
Debugging.
A debugger is a software program that allows
you to analyze the behavior of your applications to locate logic errors. At
the ends of several tutorials, we provide Using the
Debugger sections in which you will learn to detect and remove logic
errors by using the Visual Studio .NET debugger. Appendix A provides
instructions for using the GNU debugger (GDB).
Notes to the Instructor
Focus of the Book
Our goal was clear: Produce a C++
textbook for introductory-level courses in computer programming for students
with little or no programming experience. This book teaches computer
programming principles and the C++ language, including input/output, data
types, variables, pseudocode, algorithms, control statements, operators,
functions, arrays, strings, classes, objects, inheritance, polymorphism,
pointers, references, file processing, exceptions, templates, operator
overloading and more. After mastering the material, students will be able to
program in C++ and to employ its cross-platform capabilities. Note that this
book is based on ANSI/ISO standard C++. All of the programs in the book will
run on any ANSI/ISO C++ compliant compiler.
Lab Setup
Before you can compile and run the
applications in this book, Microsofts
Visual C++ .NET, or an appropriate C++ development tool, must be installed.
We discuss installing MS VC++ .NET in the Before You
Begin section that follows this Preface. For computer labs in which
students are not allowed to install software, instructors and system
administrators must ensure that appropriate C++ software is installed on the
lab computers in advance of the course.
Note Regarding
the Platform We Used to Develop the Book
We assume that students are using
Windows platform computers (Windows 2000 or Windows XP, in particular), so
all directory names, instructions and sample screen captures appear in
Windows format. However, the instructions and concepts presented work well
on most computer platforms on which ANSI/ISO Standard C++ compilers are
available, such as Linux and UNIX. [Note: All
windows that show source code were created in VC++ .NET. Copyright 19982002
Microsoft Corporation, All rights reserved. Used by permission.] If you have
questions about using the VC++ .NET software, please refer to the
documentation that comes with VC++ .NET or read our
Dive Into Series publications, which are available on our Web site
with the Simply C++ resources at
www.deitel.com/books/simplycpp1/index.html.
The free Dive-Into Series publications help
students and instructors familiarize themselves with various C++ development
tools. These publications include: Dive-Into
Microsoft Visual C++ .NET,
Dive-Into GNU C++ on Linux,
Dive-Into GNU C++ with CygWin on Windows,
Dive-Into Microsoft Visual C++
6 and Dive-Into Borland C++ 5.5.
Objectives
Each tutorial begins with
objectives that inform students of what to expect and gives them an
opportunity, after reading the tutorial, to determine whether they have met
the intended goals.
Outline
The tutorial outline enables
students to approach the material in top-down fashion. Along with the
tutorial objectives, the outline helps students anticipate future topics and
set a comfortable and effective learning pace.
Example
Applications (with Outputs)
We present C++ features in the
context of complete, working C++ applications. We call this our Live-Code approach. All examples are available on the CD that
accompanies the book or as downloads from our Web site,
www.deitel.com/books/simplycpp1/index.html.
Illustrations/Figures
An abundance of charts, line
drawings and application outputs are included. The discussion of control
statements, for example, is supported by carefully drawn UML activity
diagrams. [Note: We do not teach UML diagramming
as a program-development tool, but we do use UML diagrams to explain the
precise operation of many of C++s
control statements.]
Programming
Tips
Hundreds of
programming tips help students focus on important aspects of application
development. These tips and practices represent the best the authors have
gleaned from a combined seven decades of programming and teaching
experience.
Good Programming Practices highlight techniques
that help students write applications that are clear, understandable and
maintainable.
Students
learning a languageespecially
in their first programming coursefrequently
make errors. Pointing out these Common Programming
Errors in the text reduces the likelihood that students will make the
same mistakes.
These tips
describe aspects of C++ that prevent errors from getting into applications
in the first place, which simplifies the testing and debugging process.
Teaching
students to write clear and understandable applications is the most
important goal for a first programming course. But students want to write
applications that run the fastest, use the least memory, require the
smallest number of keystrokes, etc. Performance Tips
highlight opportunities for improving application performance.
The
Portability Tips provide insights into how C++ achieves its high
degree of portability among different platforms.
The
Software Design Tips highlight
architectural and design issues that affect the construction of
object-oriented software systems.
Skills Summary
Each tutorial includes a
bullet-list-style summary of the new programming concepts presented. This
reinforces key actions taken to build the tutorials
application.
544 Key Terms
Each tutorial includes a list of
important terms defined in the tutorial. These terms also appear in the
index and in a book-wide glossary, so the student can locate the terms and
their definitions quickly.
192 Self-Review Questions and
Answers
Self-review multiple-choice
questions and answers are included after most sections to build students
confidence with the material and prepare them for the regular exercises.
Students should be encouraged to attempt all the self-review exercises and
check their answers.
358 Exercises (Solutions in
Instructors Manual)
Each tutorial concludes with
exercises. Typical exercises include 10 multiple-choice questions, a
What does this code do?
exercise, a Whats
wrong with this code?
exercise, three regular programming exercises and a programming challenge. [Note:
In the What
does this code do? and
Whats
wrong with this code?
exercises, we show only portions of the code in the text, but the instructors
manual contains full applications with outputs.] Several tutorials also
include exercises that require students to use the C++ debugger to locate
and fix logic errors in applications. Throughout the book, we make the
assumption that the reader tries, or at least carefully reads, all of the
exercises.
The questions
involve simple recall of important terminology and concepts, writing
individual C++ statements, writing small portions of C++ applications and
writing complete C++ functions, classes and applications. Every programming
exercise uses a step-by-step methodology to guide the student. The solutions
for the exercises are available only to instructors
through their Prentice-Hall representatives. [NOTE:
Please do not write to us requesting the instructors manual.
Distribution of this publication is strictly limited to instructors teaching
from the book. Instructors may obtain the solutions manual only from their
regular Prentice Hall representatives. We regret
that we cannot provide the solutions to professionals.]
C++ Standard Library Reference
Summaries
Each tutorial includes a summary
of the classes, functions and other C++ Standard Library objects introduced
in the tutorial. The summary includes a description of each library.
Index
The extensive index includes
important terms both under main headings and as separate entries so that
students can search for any term or concept by keyword. The code examples
and the exercises are also included in the index. Every C++ source code
application in the book is indexed under both the appropriate application
and as a subindex item under applications.
We have also double-indexed features such as functions and classes. This
makes it easier to find examples using particular features.
Simply C++ Ancillary Package
Simply C++
is accompanied by extensive ancillary materials for instructors,
including the following:
n
Instructor�s
Resource CD (IRCD) which contains the
n
Instructor�s
Manual with solutions to the end-of-tutorial exercises
n
Test-Item File of multiple-choice questions
(approximately two per tutorial section)
n
Customizable PowerPoint Slides
containing all the code and figures in the text, and bulleted items that
summarize the key points in the text
Companion Web Site
The Companion
Web Site offers a Syllabus Manager, which
helps instructors plan courses interactively and create online syllabi.
Students also benefit from the functionality of the
Companion Web Site. Book-specific resources for students include:
n
Example source code
n
Reference materials from the book appendices
n
Tutorial objectives
n
Tutorial outlines
n
Programming tips from each tutorial
To access
Simply C++s
Companion Web Site, visit
www.prenhall.com/deitelญ.
PearsonChoices
Todays
students have increasing demands on their time and money, and they need to
be resourceful about how, when and where they study. Our publisher, Prentice
Hall, is owned by Pearson Education, which has responded to that need by
creating PearsonChoices to allow faculty and students to choose from a
variety of textbook formats and prices.
SafariX WebBooks
SafariX Textbooks Online is a new
service for college students looking to save money on required or
recommended textbooks for academic courses. This secure WebBooks platform
creates a new option in the higher education market; an additional choice
for students alongside conventional textbooks and online learning services.
By eliminating the costs relating to printing, manufacturing and retail
distribution for the physical textbook, Pearson provides students with a
WebBook at 50% of the cost of its conventional print equivalent.
SafariX
WebBooks are viewed through a Web browser connected to the Internet. No
special plug-ins are required and no applications need to be downloaded.
Students simply log in, purchase access and begin studying. With SafariX
Textbooks Online students will be able to search the text, make notes
online, print out reading assignments that incorporate their professors
lecture notes and bookmark important passages they want to review later.
They can navigate easily to a page number, reading assignment, or chapter.
The Table of Contents of each WebBook appears in the left hand column
alongside the text.
We are pleased
to offer students the Simply C++ SafariX WebBook
available for January 2005 classes. Visit
www.pearsonchoices.com for more
information. Other Deitel titles available as SafariX WebBooks include
Small Java How to Program, 6/e and
Java How to Program, 6/e. Visit
www.safarix.com/tour.html
for more information.
Coming Soon: OneKey Powered by
Course Compass, BlackBoard and WebCT Course Management Systems
OneKey is Prentice Halls
exclusive new resource that gives instructors and students access to the
best online teaching and learning tools through one convenient Web site.
OneKey enables instructors to prepare their courses effectively, present
their courses more dramatically and assess students easily. An abundance of
searchable presentation material together with practice activities and test
questionsall organized by
chapter or topichelps to
simplify course preparation.
Selected
content from the Deitels
introductory programming language
Simply
Series, including Simply
C++, will soon be available to integrate into various popular course
management systems, including CourseCompass, Blackboard and WebCT. Course
management systems help faculty create, manage and use sophisticated
Web-based educational tools and programs. Instructors can save hours of
inputting data by using Deitel course management systems content.
Blackboard, CourseCompass and WebCT offer:
n
Features to create and customize an online course,
such as areas to post course information (e.g., policies, syllabi,
announcements, assignments, grades, performance evaluations and progress
tracking), class and student management tools, a gradebook, reporting tools,
page tracking, a calendar and assignments.
n
Communication tools to help create and maintain
interpersonal relationships between students and instructors, including chat
rooms, whiteboards, document sharing, bulletin boards and private e-mail.
n
Flexible testing tools that allow an instructor to
create online quizzes and tests from questions directly linked to the text,
and that grade and track results effectively. All tests can be inputted into
the gradebook for efficient course management. WebCT also allows instructors
to administer timed online quizzes.
n
Support materials for instructors are available in
print and online formats.
In addition to
the types of tools found in Blackboard and WebCT, CourseCompass from
Prentice Hall includes:
n
CourseCompass course home page, which makes the
course as easy to navigate as a book. An expandable table of contents allows
instructors to view course content at a glance and to link to any section.
n
Hosting on Prentice Hall�s
centralized servers, which allows course administrators to avoid
separate licensing fees or server-space issues. Access to Prentice Hall
technical support is available.
n
�How Do I�
online-support sections are available for users who need help
personalizing course sites, including step-by-step instructions for adding
PowerPoint slides, video and more.
n
Instructor Quick Start Guide helps instructors
create online courses using a simple, step-by-step process.
To view free
online demonstrations and learn more about these Course Management Systems,
which support Deitel content, visit the following Web sites:
n
Blackboard:
www.blackboard.com and
www.prenhall.com/blackboard
n WebCT:
www.webct.com
and www.prenhall.com/webct
n
CourseCompass:
www.coursecompass.com and
www.prenhall.com/coursecompass
Acknowledgments
One of the great pleasures of
writing a textbook is acknowledging the efforts of many people whose names
may not appear on the cover, but whose hard work, cooperation, friendship
and understanding were crucial to the production of the book. Many people at
Deitel & Associates, Inc., devoted long hours to this project.
n Abbey
Deitel, President
n
Barbara Deitel, Chief Financial Officer
We would also
like to thank the participants in the Deitel & Associates, Inc., College
Internship Program who contributed to this book and its ancillaries: Tim
Christensen, Jeffrey Peng and Eric Winokur.[1]
We are
fortunate to have been able to work on this project with the talented and
dedicated team of publishing professionals at Prentice Hall. We especially
appreciate the extraordinary efforts of our Computer Science Editor, Kate
Hargett and her boss and our mentor in publishingMarcia
Horton, Editorial Director of Prentice-Halls
Engineering and Computer Science Division. Tom Manshreck and Vince OBrien
managed the production of the book. John Lovell served as production editor.
Geoff Cassar and Carole Anson worked on the cover design and Sarah Parker
handled editorial responsibilities on the books
extensive ancillary package.
We wish to
acknowledge the efforts of our reviewers and to thank Jennifer Capello of
Prentice Hall, who managed the review process. The 21 reviewers from
academia and industry adhered to a tight time schedule, these reviewers
scrutinized the text and the applications, providing countless suggestions
for improving the accuracy and completeness of the presentation. It is a
privilege to have the guidance of such talented and busy professionals.
Simply C++
Reviewers:
Mark Andersen,
Microsoft
Warren
Bartlett, Florida Metropolitan University
Edward Brunjes,
Miramar College
James Brzowski,
University of Massachusetts at Lowell
Dharmesh
Chauhan, Microsoft
Marg Chauvin,
Palm Beach Community College
Mahesh
Hariharan, Microsoft
Richard
Holladay, San Diego Mesa College
Ravinder Kang,
Highline Community College
Don Kostuch,
Independent Consultant
Kriang
Lerdsuwanakij, Siemens Limited Thailand (GCC Development team)
Ami Neiman,
DeVry University, Fremont
Gavin Osborne,
Saskatchewan Institute of Applied Science and Technology
Tom Pennings,
Borland Software Corporation
Judy Scholl,
Austin Community College
Ray
Stephenson, Microsoft
William
Tucker, Austin Community College
John Varghese,
UBS Warburg
Jeff Welton,
Microsoft
Ellen
Williams, Atlantic Technical Center
Catherine
Wyman, DeVry University, Phoenix
We would
sincerely appreciate your comments, criticisms, corrections and suggestions
for improving this textbook. Please address all correspondence to:
deitel@deitel.com
We will respond promptly.
Well, thats
it for now. Welcome to the exciting world of C++ programming. We hope you
enjoy this first look at C++ applications development. Good luck!
Dr. Harvey
M. Deitel
Paul J. Deitel
Dave Choffnes
Christi Kelsey
About the Authors
Dr. Harvey M.
Deitel, Chairman and Chief Strategy Officer of Deitel & Associates,
Inc., has 43 years experience in the computing field, including extensive
industry and academic experience. Dr. Deitel earned B.S. and M.S. degrees
from the Massachusetts Institute of Technology and a Ph.D. from Boston
University. He worked on the pioneering virtual-memory operating-systems
projects at IBM and MIT that developed techniques now widely implemented in
systems such as UNIX, Linux and Windows XP. He has 20 years of college
teaching experience and served as the Chairman of the Computer Science
Department at Boston College before founding Deitel & Associates, Inc., with
his son, Paul J. Deitel. He is the author or co-author of several dozen
books and multimedia packages. With translations published in numerous
foreign languages, Dr. Deitels
texts have earned international recognition. Dr. Deitel has delivered
hundreds of professional seminars to major corporations, academic
institutions, government organizations and various branches of the military.
Paul J. Deitel, CEO and Chief Technical Officer of
Deitel & Associates, Inc., is a graduate of the Massachusetts Institute of
Technologys Sloan School
of Management, where he studied information technology. Through Deitel &
Associates, Inc., he has delivered professional seminars to numerous
industry and government clients and has lectured on C++ for the Boston
Chapter of the Association for Computing Machinery. He and his father, Dr.
Harvey M. Deitel, are the worlds
best-selling Computer Science textbook authors.
David R. Choffnes is a graduate of Amherst College
magna cum laude with degrees in Physics and
French. During his time at Amherst, he also completed significant course
work in computer science. David contributed to Simply
Visual Basic .NET
and co-authored Operating Systems, 3/e with the
Deitels. In his spare time, he designs Web sites and develops a content
management system. David is the recipient of a Cabell Fellowship at
Northwestern University, where he will pursue a Ph.D. in Computer Science
beginning in the Fall of 2004.
Christiann L. Kelsey, Director of Business
Development at Deitel & Associates, Inc., graduated from Purdue University
with a degree in management and information systems. Christi has contributed
to several Deitel & Associates, Inc. publications including
Wireless Internet & Mobile Business How to Program;
Internet & World Wide Web How to Program, 3/e;
Java How to Program, 6/e;
Simply Visual Basic .NET 2003; Simply Java
Programming; Simply C# and many others.
Christi is also responsible for the Deitel
Buzz Online e-mail
newsletter and the Deitel Dive Into Series Corporate Training business.
About Deitel & Associates, Inc.
Deitel & Associates, Inc., is an
internationally recognized corporate-training and content-creation
organization specializing in computer programming languages, object
technology and Internet/World Wide Web software technology education.
Through its 28-year publishing partnership with Prentice Hall, Deitel &
Associates, Inc. publishes leading-edge programming textbooks, professional
books, interactive multimedia Cyber Classrooms
and course management systems e-content.
To learn more
about Deitel & Associates, Inc., its Prentice Hall publications and its
worldwide Dive Into Series Corporate Training curriculum, see the last few
pages of this book or visit:
www.deitel.com
and subscribe to the free
Deitel
Buzz Online e-mail newsletter at:
www.deitel.com/newsletter/subscribe.html
Individuals
wishing to purchase Deitel books, Cyber Classrooms
and Complete Training Courses can do so through
bookstores, or online booksellers and:
www.deitel.com
www.prenhall.com/deitel
www.InformIT.com/deitel
Bulk orders by
corporations and academic institutions should be placed directly with Prentice
Hall. For ordering information, please visit:
www.prenhall.com/deitel
The Deitel Buzz Online
e-Mail Newsletter
Our free e-mail newsletter includes
links to articles and resources from our published books and upcoming
publications, information on future publications, product-release schedules,
information on corporate training, crossword puzzles using computing
terminology and more. For quick opt-in registration, visit
www.deitel.com/newsletter/subscribe.html
|