|
C++ How to Program, 5/e
Preface
“The
chief merit of language is clearness ”
—Galen
Welcome to C++ and
C++ How to Program, Fifth Edition! C++ is a world-class programming
language for developing industrial-strength, high-performance computer
applications. We believe that this book and its support materials have
everything instructors and students need for an informative, interesting,
challenging and entertaining C++ educational experience. In this Preface, we
overview the many new features of C++ How to Program,
5/e. The Tour of the Book section of the
Preface gives instructors, students and professionals a sense of
C++ How to Program, 5/e’s coverage of C++ and object-oriented
programming. We also overview various conventions used in the book, such as
syntax coloring the code examples, “code washing” and code highlighting. We
provide information about free compilers that you can find on the Web. We
also discuss the comprehensive suite of educational materials that help
instructors maximize their students’ learning experience, including the
Instructor’s Resource CD, PowerPoint Slide lecture notes,
course management systems, SafariX (Pearson Education’s WebBook
publications) and more.
Features of C++ How to Program, 5/e
At Deitel & Associates, we write
college-level computer science textbooks and professional books. To
create C++ How to Program, 5/e, we put
the previous edition of C++ How to Program under
the microscope. The new edition has many compelling features:
• Major Content Revisions. All the chapters
have been significantly updated and upgraded. We tuned the writing for
clarity and precision. We also adjusted our use of C++ terminology in
accordance with the ANSI/ISO C++ standard document that defines the
language.
• Smaller Chapters. Larger chapters have been
divided into smaller, more manageable chapters (e.g., Chapter 1 of the
Fourth Edition has been split into Chapters 1–2; Chapter 2 of the Fourth
Edition is now Chapters 4–5).
• Early Classes and Objects Approach. We
changed to an early classes and objects pedagogy. Students are introduced to
the basic concepts and terminology of object technology in Chapter 1. In the
previous edition, students began developing customized, reusable classes and
objects in Chapter 6, but in this edition, they do so in our completely new
Chapter 3. Chapters 4–7 have been carefully rewritten from an “early classes
and objects” perspective. This new edition is object oriented, where
appropriate, from the start and throughout the text. Moving the discussion
of objects and classes to earlier chapters gets students “thinking about
objects” immediately and mastering these concepts more completely. Object-ori•
ented programming is not trivial by any means, but it’s fun to write
object-oriented programs, and students can see immediate results.
• Integrated Case Studies. We have added several
case studies spanning multiple sections and chapters that often build on a
class introduced earlier in the book to demonstrate new programming concepts
later in the book. These case studies include the development of the
GradeBook class
in Chapters 3–7, the Time
class in several sections of Chapters 9–10, the
Employee class in Chapters 12–13,
and the optional OOD/UML ATM case study in chapters 1-7, 9, 13 and Appendix G.
• Integrated
GradeBook Case
Study. We added a new
GradeBook case study to reinforce our early classes
presentation. It uses classes and objects in Chapters 3–7 to incrementally
build a GradeBook
class that represents an instructor’s grade book and performs various
calculations based on a set of student grades, such as calculating the average
grade, finding the maximum and minimum and printing a bar chart.
• Unified Modeling Language 2.0 (UML 2.0)—Introducing
the UML 2.0. The Unified Modeling Language (UML) has become the
preferred graphical modeling language for designers of object-oriented
systems. All the UML diagrams in the book comply with the new UML 2.0
specification. We use UML class diagrams to visually represent classes and
their inheritance relationships, and we use UML activity diagrams to
demonstrate the flow of control in each of C++’s control statements. We make
especially heavy use of the UML in the optional OOD/UML ATM case study
• Optional OOD/UML ATM Case Study. We replaced
the optional elevator simulator case study from the previous edition with a
new optional OOD/UML automated teller machine (ATM) case study in the Software
Engineering Case Study sections of Chapters 1–7, 9 and 13. The new case study
is simpler, smaller, more “real world” and more appropriate for first and
second programming courses. The nine case study sections present a carefully
paced introduction to object-oriented design using the UML. We
introduce a concise, simplified subset of the UML 2.0, then guide the reader
through a first design experience intended for the novice object-oriented
designer/programmer. Our goal in this case study is to help students
develop an object-oriented design to complement the object-oriented
programming concepts they begin learning in Chapter 1 and implementing in
Chapter 3. The case study was reviewed by a distinguished team of OOD/UML
academic and industry professionals. The case study is not an exercise;
rather, it is a fully developed end-to-end learning experience that concludes
with a detailed walkthrough of the complete 877-line C++ code implementation.
We take a detailed tour of the nine sections of this case study later in the
Preface.
• Compilation and Linking Process for
Multiple-Source-File Programs. Chapter 3 includes a detailed diagram
and discussion of the compilation and linking process that produces an
executable application.
• Function Call Stack Explanation. In Chapter 6,
we provide a detailed discussion (with illustrations) of the function call
stack and activation records to explain how C++ is able to keep track of which
function is currently executing, how au• tomatic variables of
functions are maintained in memory and how a function knows where to return
after it completes execution.
• Early Introduction of C++ Standard Library
string
and vector
Objects. The string
and vector
classes are used to make earlier examples more object-oriented.
• Class
string.
We use class string
instead of C-like pointer-based
char
* strings for most string
manipulations throughout the book. We continue to include discussions of
char * strings
in Chapter 8, 10, 11 and 22 to give students practice with pointer
manipulations, to illustrate dynamic memory allocation with
new and
delete, to build our own
String class,
and to prepare students for assignments in industry where they will work with
char
* strings in C
and C++ legacy code.
• Class Template
vector.
We use class template vector
instead of C-like pointer-based array manipulations throughout the book.
However, we begin by discussing C-like pointer-based arrays in Chapter 7 to
prepare students for working with C and C++ legacy code in industry and to use
as a basis for building our own customized
Array class in Chapter 11,
Operating Overloading.
• Tuned Treatment of Inheritance and Polymorphism.
Chapters 12–13 have been carefully tuned, making the treatment of
inheritance and polymorphism clearer and more accessible for students who are
new to OOP. An Employee
hierarchy replaces the Point/Circle/Cylinder
hierarchy used in prior editions to introduce inheritance and polymorphism.
The new hierarchy is more natural.
• Discussion and Illustration of How Polymorphism Works
“Under the Hood.” Chapter 13 contains a detailed diagram and
explanation of how C++ can implement polymorphism,
virtual functions and dynamic
binding internally. This gives students a solid understanding of how these
capabilities really work. More importantly, it helps students appreciate the
overhead of polymorphism—in terms of additional memory consumption and
processor time. This helps students determine when to use polymorphism and
when to avoid it.
• Web Programming. Chapter 19, Web Programming, has everything
readers need to begin developing their own Web-based applications that will
run on the Internet! Students will learn how to build so-called
n-tier applications, in which the functionality
provided by each tier can be distributed to separate computers across the
Internet or executed on the same computer. Using the popular Apache HTTP
server (which is available free for download from
www.apache.org) we present the CGI
(common Gateway Interface) protocol and discuss how CGI allows a Web server to
communicate with the top tier (e.g., a Web browser running on the user’s
computer) and CGI scripts (i.e., our C++ programs) executing on a remote
system. The chapter examples conclude with an e-business case study of an
online bookstore that allows users to add books to an electronic shopping
cart.
• Standard Template Library (STL). This might be one of the most
important topic in the book in terms of your appreciation of software reuse.
The STL defines powerful, template-based, reusable components that implement
many common data structures and algorithms used to process those data
structures. Chapter 23 introduces the STL and discusses its three key
components—containers, iterators and algorithms. We show that using STL
components provides • tremendous expressive power and can reduce many
lines of code to a single statement.
• XHTML.
The World Wide Web Consortium (W3C) has declared HyperText
Markup Language (HTML) to be a legacy technology that will undergo no further
development. HTML is being replaced by the Extensible HyperText Markup
Language (XHTML)—an XML-based technology that rapidly is becoming the standard
for describing Web content. We use XHTML in Chapter 19, Web
Programming; Appendix J and Appendix K introduce XHTML.
•
ANSI/ISO C++ Standard Compliance. We have audited
our presentation against the most recent ANSI/ISO C++ standard document for
completeness and accuracy. [Note: If you need
additional technical details on C++, you may want to read the C++ standard
document. An electronic PDF copy of the C++ standard document, number INCITS/ISO/IEC
14882-2003, is available for $18 at
webstore.ansi.org/ansidocstore/default.asp.]
•
New Debugger Appendices. We include two new Using
the Debugger appendices—Appendix L, Using the Visual Studio .NET Debugger, and
Appendix M, Using the GNU C++ Debugger.
•
New Interior Design. Working with the creative
services team at Prentice Hall, we redesigned the interior styles for our
How to Program Series. The new fonts are easier on the eyes and the new
art package is more appropriate for the more detailed illustrations. We now
place the defining occurrence of each key term both in the text and in the
index in blue, bold style text for easier
reference. We emphasize on-screen components in the bold
Helvetica font (e.g., the
File menu) and
emphasize C++ program text in the
Lucida font (e.g.,
int
x
= 5).
•
Syntax Coloring. We syntax color all the C++ code,
which is consistent with most C++ integrated development environments and code
editors. This greatly improves code readability—an especially important goal,
given that this book contains 17,292 lines of code. Our syntax-coloring
conventions are as follows:
keywords appear in dark blue
constants and literal values appear in light
blue
errors appear in red
all other code appears in black
•
Code Highlighting. Extensive code highlighting makes
it easy for readers to locate each program’s new features and helps students
review the material rapidly when preparing for exams or labs.
•
“Code washing.” This is our term for using extensive
and meaningful comments, using meaningful identifiers, applying uniform
indentation conventions, aligning curly braces vertically, using a
// end...
comment on every line with a right curly brace and using vertical spacing to
highlight significant program units such as control statements and functions.
This process results in programs that are easy to read and self-documenting.
We have extensively “code washed” all of the source-code programs in both the
text and the book’s ancillaries. We have worked hard to make our code
exemplary.
•
Code Testing on Multiple Platforms. We tested the
code examples on various popular C++ platforms. For the most part, all of the
book’s examples port easily to all popular ANSI/ISO standard-compliant
compilers. We will post any problems at
www.deitel.com/books/cpphtp5/index.html.
•
Errors and Warnings Shown for Multiple Platforms.
For programs that intentionally contain errors to illustrate a key concept, we
show the error messages that result on several popular platforms.
• Large Review Team. The book has been carefully
scrutinized by a team of 30 distinguished academic and industry reviewers
(listed later in the Preface).
• Free Web-Based Cyber
Classroom. We’ve converted our
popular interactive multimedia version of the text (which we call a
Cyber Classroom) from a for-sale, CD-based product
to a free online supplement, available with new books purchased from Prentice
Hall for fall 2005 classes.
•
Free Student Solutions Manual. We’ve converted our
Student Solutions Manual, which contains solutions to approximately half of
the exercises, from a for-sale softcover book to a free online supplement,
available with new books purchased from Prentice Hall for fall 2005 classes.
•
Free Lab Manual. We’ve converted our Lab Manual,
C++ in the Lab, from a for-sale softcover book to
a free online supplement included with the Cyber
Classroom, available with new books purchased from Prentice Hall for
fall 2005 classes.
As you read this
book, if you have questions, send an e-mail to
deitel@deitel.com; we will respond
promptly. Please visit our Web site,
www.deitel.com and be sure to sign
up for the free Deitel
Buzz Online e-mail newsletter at
www.deitel.com/newsletter/subscribe.html
for updates to this book and the latest information on C++. We also use the
Web site and the newsletter to keep our readers and industry clients informed
of the latest news on Deitel publications and services. Please check the
following Web site regularly for errata, updates regarding the C++ software,
free downloads and other resources:
www.deitel.com/books/cpphtp5/index.html
Teaching Approach
C++ How to
Program, 5/e contains an abundant collection of examples, exercises and
projects drawn from many fields to provide the student with a chance to solve
interesting real-world problems. The book concentrates on the principles of
good software engineering and stresses program clarity. We avoid arcane
terminology and syntax specifications in favor of teaching by example. We are
educators who teach programming languages courses in industry classrooms
worldwide. Dr. Harvey M. Deitel has 20 years of college teaching experience,
including serving as chairman of the Computer Science Department at Boston
College, and 15 years of industry teaching experience. Paul Deitel has 12
years of industry teaching experience. The Deitels have taught C++ courses at
all levels to the government, industry, military and academic clients of
Deitel & Associates.
Learning C++ using the Live-Code
Approach
C++ How to Program, 5/e, is
loaded with C++ programs—each new concept is presented in the context of a
complete working C++ program that is immediately followed by one or more
sample executions showing the program’s inputs and outputs. This style
exemplifies the way we teach and write about programming. We call this method
of teaching and writing the Live-Code Approach. We use
programming languages to teach programming languages. Reading the
examples in the text is much like typing and running them on a computer. We
provide all the source code for the book’s examples on the accompanying CD and
at www.deitel.com—making
it easy for students to run each example as they study it.
World Wide Web Access
All the source-code examples for
C++ How to Program, 5/e (and our other publications) are available on the
Internet as downloads from
www.deitel.com
Registration is quick and easy, and
the downloads are free. We suggest downloading all the examples (or copying
them from the CD included in the back of this book), then running each program
as you read the corresponding text. Making changes to the examples and
immediately seeing the effects of those changes is a great way to enhance your
C++ learning experience.
Objectives
Each chapter begins with a statement
of objectives. This lets students know what to expect and gives them an
opportunity, after reading the chapter, to determine if they have met these
objectives. This is a confidence builder and a source of positive
reinforcement.
Quotations
The learning objectives are followed
by quotations. Some are humorous, some philosophical and some offer
interesting insights. We hope that you will enjoy relating the quotations to
the chapter material. Many of the quotations are worth a second look after
reading the chapter.
Outline
The chapter outline helps students
approach the material in a top-down fashion, so they can anticipate what is to
come, and set a comfortable and effective learning pace.
17,292 Lines of Syntax-Colored Code
in 260 Example Programs with Program Inputs and Outputs)
Our
Live-Code programs range in size
from just a few lines of code to more substantial examples. Each program is
followed by a window containing the input/output dialogue produced when the
program is run, so students can confirm that the programs run as expected.
Relating outputs to the program statements that produce them is an excellent
way to learn and to reinforce concepts. Our programs demonstrate the diverse
features of C++. The code is line-numbered and syntax colored—with C++
keywords, comments and other program text each appearing in different colors.
This facilitates reading the code—students will especially appreciate the
syntax coloring when they read the larger programs.
735 Illustrations/Figures
An abundance of charts, tables, line
drawings, programs and program outputs is included. We model the flow of
control in control statements with UML activity diagrams. UML class diagrams
model the data members, constructors and member functions of classes. We use
additional types of UML diagrams throughout our optional OOD/UML ATM Software
Engineering Case Study.
571 Programming Tips
We include programming tips to help
students focus on important aspects of program development. We highlight these
tips in the form of Good Programming Practices,
Common Programming Errors,
Performance Tips, Portability Tips,
Software Engineering Observations and
Error-Prevention Tips. These tips and practices
represent the best we have gleaned from a combined six decades of programming
and teaching experience. One of our students, a mathematics major, told us
that she feels this approach is like the highlighting of axioms, theorems,
lemmas and corollaries in mathematics books—it provides a basis on which to
build good software.
Good
Programming Practices
i.0Good
Programming Practices are tips for writing clear programs. These
techniques help students produce programs that are more readable,
self-documenting and easier to maintain.
Common Programming Errors
i.0Students who
are new to programming (or a programming language) tend to make certain errors
frequently. Focusing on these Common Programming Errors
reduces the likelihood that students will make the same mistakes and shortens
long lines outside instructors’ offices during office hours!
Performance Tips
iIn our
experience, teaching students to write clear and understandable programs is by
far the most important goal for a first programming course. But students want
to write the programs that run the fastest, use the least memory, require the
smallest number of keystrokes or dazzle in other nifty ways. Students really
care about performance. They want to know what they can do to “turbo charge”
their programs. So we highlight opportunities for improving program
performance—making programs run faster or minimizing the amount of memory that
they occupy.
Portability Tips
i.0Software
development is a complex and expensive activity. Organizations that develop
software must often produce versions customized to a variety of computers and
operating systems. So there is a strong emphasis today on portability, i.e.,
on producing software that will run on a variety of computer systems with few,
if any, changes. Some programmers assume that if they implement an
application in standard C++, the application will be portable. This simply is
not the case. Achieving portability requires careful and cautious design.
There are many pitfalls. We include Portability Tips to
help students write portable code and to provide insights on how C++ achieves
its high degree of portability.
Software Engineering Observations
i.0The
object-oriented programming paradigm necessitates a complete rethinking of the
way we build software systems. C++ is an effective language for achieving good
software engineering. The Software Engineering Observations
highlight architectural and design issues that affect the construction of
software systems, especially large-scale systems. Much of what the student
learns here will be useful in upper-level courses and in industry as the
student begins to work with large, complex real-world systems.
Error-Prevention Tips
i.0When we
first designed this “tip type,” we thought we would use it strictly to tell
people how to test and debug C++ programs. In fact, many of the tips describe
aspects of C++ that reduce the likelihood of “bugs” and thus simplify the
testing and debugging processes.
Wrap-Up Sections
Each chapter ends with additional
pedagogical devices. New in this edition, each chapter ends with a brief
“wrap-up” section that recaps the topics that were presented. The wrap-ups
also help the student transition to the next chapter.
Summary (1126
Summary bullets)
We present a thorough,
bullet-list-style summary at the end of every chapter. On average, there are
40 summary bullets per chapter. This focuses the student’s review and
reinforces key concepts.
Terminology
(1682 Terms)
We include an alphabetized list of
the important terms defined in each chapter—again, for further reinforcement.
There is an average of 82 terms per chapter. Each term also appears in the
index, and the defining occurrence of each term is highlighted in the index
with a blue, bold page number so the student can
locate the definitions of key terms quickly.
609 Self-Review
Exercises and Answers (Count Includes Separate Parts)
Extensive self-review exercises and
answers are included in each chapter. This gives the student a chance to build
confidence with the material and prepare for the regular exercises. We
encourage students to do all the self-review exercises and check their
answers.
849 Exercises
(Solutions in Instructor’s Manual; Count Includes Separate Parts)
Each chapter concludes with a
substantial set of exercises including simple recall of important terminology
and concepts; writing individual C++ statements; writing small portions of C++
functions and classes; writing complete C++ functions, classes and programs;
and writing major term projects. The large number of exercises enables
instructors to tailor their courses to the unique needs of their audiences and
to vary course assignments each semester. Instructors can use these exercises
to form homework assignments, short quizzes and major examinations. The
solutions for the vast majority of the exercises are included on the
Instructor’s Resource CD (IRCD),
which is available only to instructors
through their Prentice Hall representatives. [NOTE: Please
do not write to us requesting the Instructor’s CD. Distribution of this
ancillary is limited strictly to college instructors teaching from the book.
Instructors may obtain the solutions manual only from their Prentice Hall
representatives.] Students will have access to approximately half the
exercises in the book in the free, Web-based Cyber
Classroom which will be available in late spring 2005. For more
information about the Cyber Classroom, please
visit www.deitel.com
or sign up for the free Deitel
Buzz Online e-mail newsletter at
www.deitel.com/newsletter/subscribe.html.
Approximately 6,000 Index Entries
We have included an extensive index.
This helps students find terms or concepts by keyword. The index is useful to
people reading the book for the first time and is especially useful to
practicing programmers who use the book as a reference.
“Double Indexing” of All C++ Live-Code
Examples
C++ How to Program, 5/e has
260 live-code examples and 849 exercises (including separate parts). We have
double indexed each of the live-code examples and most of the more substantial
exercises. For every source-code program in the book, we indexed the figure
caption both alphabetically and as a subindex item under “Examples.” This
makes it easier to find examples using particular features. The more
substantial exercises are also indexed both alphabetically and as subindex
items under “Exercises.”
Tour of
the Book
In this section, we take a tour of the many
capabilities of C++ you will study in C++ How to Program, 5/e. Figure 1
illustrates the dependencies among the chapters. We recommend studying these
topics in the order indicated by the arrows, though other orders are possible.
This book is widely used in all levels of C++ programming courses. Search the
Web for “syllabus,” “C++” and “Deitel” to find syllabi used with recent
editions of this book.
Chapter 1—Introduction to Computers, the Internet and World Wide Web—discusses
what computers are, how they work and how they are programmed. The chapter
gives a brief history of the development of programming languages from machine
languages to assembly languages and high-level languages. The origin of the
C++ programming language is discussed. Our free
Dive-Into Series publications for other platforms are available at
www.deitel.com/books/downloads.html.
The chapter includes an introduction to a typical C++ programming environment.
We walk readers through a “test drive” of a typical C++ application on Windows
and Linux platforms. This chapter also introduces basic object technology
concepts and terminology and the Unified Modeling Language.
Chapter 2—Introduction to C++ Programming—provides a lightweight
introduction to programming applications in the C++ programming language. The
chapter introduces nonprogrammers to basic programming concepts and
constructs. The programs in this chapter illustrate how to display data on the
screen and how to obtain data from the user at the keyboard. Chapter 2 ends
with detailed treatments of decision making and arithmetic operations.
Chapter 3—Introduction to Classes and Objects—is the “featured”
chapter for the new edition. It provides a friendly early introduction to
classes and objects. Carefully developed and completely new in this edition,
Chapter 3 gets students working with object orientation comfortably from the
start. It was developed with the guidance of a distinguished team of industry
and academic reviewers. We introduce classes, objects, member functions,
constructors and data members using a series of simple real-world examples. We
develop a well-engineered framework for organizing object-oriented programs in
C++. First, we motivate the notion of classes with a simple example. Then we
present a carefully paced sequence of seven complete working programs to
demonstrate creating and using your own classes. These examples begin our
integrated case study on developing a grade-book class
that instructors can use to maintain student test scores. This case study is
enhanced over the next several chapters, culminating with the version
presented in Chapter 7, Arrays and Vectors. The
GradeBook class case study
describes how to define a class and how to use it to create an object. The
case study discusses how to declare and define member functions to implement
the class’s behaviors, how to declare data members to implement the class’s
attributes and how to call an object’s member functions
to make them perform their tasks. We introduce C++ Standard Library class
string
and create string
objects to store the name of the course that a
GradeBook
object represents. Chapter 3 explains the differences between data members of
a class and local variables of a function and how to use a constructor to
ensure that an object’s data is initialized when the object is created. We
show how to promote software reusability by separating a class definition from
the client code (e.g., function
main)
that uses the class. We also introduce another fundamental principle of good
software engineering—separating interface from implementation. The chapter
includes a detailed diagram and discussion explaining the compilation and
linking process that produces an executable application.
Chapter 4—Control Statements: Part 1—focuses on the
program-development process involved in creating useful classes. The chapter
discusses how to take a problem statement and develop a working C++ program
from it, including performing intermediate steps in pseudocode. The chapter
introduces some simple control statements for decision making (if
and if
else) and
repetition (while).
We examine counter-controlled and sentinel-controlled repetition using the
GradeBook
class from Chapter 3, and introduce C++’s increment,
decrement and assignment operators. The chapter includes
two enhanced versions of the
GradeBook class,
each based on Chapter 3’s final version. These versions each include a member
function that uses control statements to calculate the average of a set of
student grades. In the first version, the member function uses
counter-controlled repetition to input 10 student grades from the user, then
determines the average grade. In the second version, the member function uses
sentinel-controlled repetition to input an arbitrary number of grades from the
user, then calculates the average of the grades that were entered. The chapter
uses simple UML activity diagrams to show the flow of control through each of
the control statements.
Chapter 5—Control Statements: Part 2—continues the discussion of
C++ control statements with examples of the
for repetition statement, the
do...while
repetition statement, the
switch selection statement, the
break statement and the
continue
statement. We create an enhanced version of class
GradeBook that
uses a switch
statement to count the number of A, B, C, D and F grades entered by the user.
This version uses sentinel-controlled repetition to input the grades. While
reading the grades from the user, a member function modifies data members that
keep track of the count of grades in each letter grade category. Another
member function of the class then uses these data members to display a summary
report based on the grades entered. The chapter includes a discussion of
logical operators.
Chapter 6—Functions and an Introduction to Recursion—takes a
deeper look inside objects and their member functions. We discuss C++
Standard-Library functions and examine more closely how students can build
their own functions. The techniques presented in Chapter 6 are essential to
the production of properly organized programs, especially the kinds of larger
programs and software that system programmers and application programmers are
likely to develop in real-world applications. The “divide and conquer”
strategy is presented as an effective means for solving complex problems by
dividing them into simpler interacting components. The chapter’s first example
continues the
GradeBook
class case study with an example of a function with multiple
parameters. Students will enjoy the chapter’s treatment of random numbers and
simulation, and the discussion of the dice game of craps, which makes elegant
use of control statements. The chapter discusses the so-called “C++
enhancements to C,” including
inline functions, reference parameters, default arguments, the
unary scope resolution operator, function overloading and function templates.
We also present C++’s call-by-value and call-by-reference capabilities. The
header files table introduces many of the header files that the reader will
use throughout the book. In this new edition, we provide a detailed discussion
(with illustrations) of the function call stack and activation records to
explain how C++ is able to keep track of which function is currently
executing, how automatic variables of functions are maintained in memory and
how a function knows where to return after it completes execution. The chapter
then offers a solid introduction to recursion and includes a table summarizing
the recursion examples and exercises distributed throughout the remainder of
the book. Some texts leave recursion for a chapter late in the book; we feel
this topic is best covered gradually throughout the text. The extensive
collection of exercises at the end of the chapter includes several classic
recursion problems, including the Towers of Hanoi.
Chapter 7—Arrays and Vectors—explains how to process lists and
tables of values. We discuss the structuring of data in arrays of data items
of the same type and demonstrate how arrays facilitate the tasks performed by
objects. The early parts of this chapter use C-style, pointer-based arrays,
which, as you will see in Chapter 8, are really pointers to the array contents
in memory. We then present arrays as full-fledged objects in the last section
of the chapter, where we introduce the C++ Standard Library
vector class template—a robust
array data structure. The chapter presents numerous examples of both
one-dimensional arrays and two-dimensional arrays. Examples in the chapter
investigate various common array manipulations, printing bar charts, sorting
data and passing arrays to functions. The chapter includes the
final two
GradeBook case
study sections, in which we use arrays to store student grades for the
duration of a program’s execution. Previous versions of the class process a
set of grades entered by the user, but do not maintain the individual grade
values in data members of the class. In this chapter, we use arrays to enable
an object of the GradeBook
class to maintain a set of grades in memory, thus eliminating the need to
repeatedly input the same set of grades. The first version of the class stores
the grades in a one-dimensional array and can produce a report containing the
average of the grades, the minimum and maximum grades and a bar chart
representing the grade distribution. The second version (i.e., the final
version in the case study) uses a two-dimensional array to store the grades of
a number of students on multiple exams in a semester. This version can
calculate each student’s semester average, as well as the minimum and maximum
grades across all grades received for the semester. The class also produces a
bar chart displaying the overall grade distribution for the semester. Another
key feature of this chapter is the discussion of elementary sorting and
searching techniques. The end-of-chapter exercises include a variety of
interesting and challenging problems, such as improved sorting techniques, the
design of a simple airline reservations system, an introduction to the concept
of turtle graphics (made famous in the LOGO language) and the Knight’s Tour
and Eight Queens problems that introduce the notion of heuristic programming
widely employed in the field of artificial intelligence. The exercises
conclude with many recursion problems including selection sort, palindromes,
linear search, the Eight Queens, printing an array, printing a string
backwards and finding the minimum value in an array.
Chapter 8—Pointers and Pointer-Based Strings—presents
one of the most powerful features of the C++ language—pointers. The chapter
provides detailed explanations of pointer operators, call by reference,
pointer expressions, pointer arithmetic, the relationship between pointers and
arrays, arrays of pointers and pointers to functions. We demonstrate how to
use const with
pointers to enforce the principle of least privilege to build more robust
software. We also introduce and using the
sizeof operator to determine the
size of a data type or data items in bytes during program compilation. There
is an intimate relationship between pointers, arrays and C-style strings in
C++, so we introduce basic C-style string-manipulation concepts and discuss
some of the most popular C-style string-handling functions, such as
getline (input a
line of text), strcpy
and strncpy
(copy a string), strcat
and strncat
(concatenate two strings),
strcmp and
strncmp (compare two strings),
strtok (“tokenize” a string into
its pieces) and strlen
(return the length of a string). In this new edition, we use
string objects (introduced in
Chapter 3) in place of C-style,
char
* pointer-based strings wherever
possible. However, we include
char *
strings in Chapter 8 to help the reader master pointers and prepare for the
professional world in which the reader will see a great deal of C legacy code
that has been implemented over the last three decades. Thus, the reader will
become familiar with the two most prevalent methods of creating and
manipulating strings in C++. Many people find that the topic of pointers is,
by far, the most difficult part of an introductory programming course. In C
and “raw C++” arrays and strings are pointers to array and string contents in
memory (even function names are pointers). Studying this chapter carefully
should reward you with a deep understanding of pointers. The chapter is loaded
with challenging exercises. The chapter exercises include a simulation of the
classic race between the tortoise and the hare, card-shuffling and dealing
algorithms, recursive quicksort and recursive maze traversals. A special
section entitled Building Your Own Computer also is included. This section
explains machine-language programming and proceeds with a project involving
the design and implementation of a computer simulator that leads the student
to write and run machine-language programs. This unique feature of the text
will be especially useful to the reader who wants to understand how computers
really work. Our students enjoy this project and often implement substantial
enhancements, many of which are suggested in the exercises. A second special
section includes challenging string-manipulation exercises related to text
analysis, word processing, printing dates in various formats, check
protection, writing the word equivalent of a check amount, Morse Code and
metric-to-English conversions.
Chapter 9—Classes: A Deeper Look, Part 1—continues our
discussion of object-oriented programming. This chapter uses a rich
Time class case study to illustrate accessing class
members, separating interface from implementation, using access functions and
utility functions, initializing objects with constructors, destroying objects
with destructors, assignment by default memberwise copy and software
reusability. Students learn the order in which constructors and destructors
are called during the lifetime of an object. A modification of the
Time case study
demonstrates the problems that can occur when a member function returns a
reference to a private
data member, which breaks the encapsulation of the class. The chapter
exercises challenge the student to develop classes for times, dates,
rectangles and playing tic-tac-toe. Students generally enjoy game-playing
programs. Mathematically inclined readers will enjoy the exercises on creating
class Complex (for complex numbers), class
Rational (for rational numbers)
and class HugeInteger
(for arbitrarily large integers).
Chapter 10—Classes: A Deeper Look, Part 2—continues the study of
classes and presents additional object-oriented programming concepts. The
chapter discusses declaring and using constant objects, constant member
functions, composition—the process of building classes that have objects of
other classes as members,
friend functions and
friend classes that have special
access rights to the private
and protected
members of classes, the this
pointer, which enables an object to know its own address, dynamic memory
allocation, static
class members for containing and manipulating class-wide data, examples of
popular abstract data types (arrays, strings and queues), container classes
and iterators. In our discussion of
const objects, we mention keyword
mutable which is
used in a subtle manner to enable modification of “non-visible” implementation
in const
objects. We discuss dynamic memory allocation using
new and
delete. When
new fails, the program terminates
by default because new
“throws an exception” in standard C++. We motivate the discussion of
static class
members with a video-game-based example. We emphasize how important it is to
hide implementation details from clients of a class; then, we discuss proxy
classes, which provide a means of hiding implementation (including the
private data in
class headers) from clients of a class. The chapter exercises include
developing a savings-account class and a class for holding sets of integers.
Chapter 11—Operator Overloading; String and Array Objects—presents
one of the most popular topics in our C++ courses. Students really enjoy this
material. They find it a perfect match with the detailed discussion of
crafting valuable classes in Chapters 9 and 10. Operator overloading enables
the programmer to tell the compiler how to use existing operators with objects
of new types. C++ already knows how to use these operators with objects of
built-in types, such as integers, floats and characters. But suppose that we
create a new String
class—what would the plus sign mean when used between
String objects? Many programmers use plus (+)
with strings to mean concatenation. In Chapter 11, the programmer will learn
how to “overload” the plus sign, so when it is written between two
String objects
in an expression, the compiler will generate a function call to an “operator
function” that will concatenate the two
Strings. The chapter discusses the
fundamentals of operator overloading, restrictions in operator overloading,
overloading with class member functions vs. with nonmember functions,
overloading unary and binary operators and converting between types. Chapter
11 features the collection of substantial case studies including an array
class, a String
class, a date class, a huge integer class and a complex numbers class (the
last two appear with full source code in the exercises). Mathematically
inclined students will enjoy creating the
polynomial class in the exercises.
This material is different from most programming languages and courses.
Operator overloading is a complex topic, but an enriching one. Using operator
overloading wisely helps you add extra “polish” to your classes. The
discussions of class Array
and class String
are particularly valuable to students who have already used the C++ Standard
Library string
class and vector
class template that provide similar capabilities. The exercises encourage the
student to add operator overloading to classes
Complex,
Rational and
HugeInteger to enable convenient
manipulation of objects of these classes with operator symbols—as in
mathematics—rather than with function calls as the student did in the Chapter
10 exercises.
Chapter 12—Object-Oriented Programming: Inheritance—introduces
one of the most fundamental capabilities of object-oriented programming
languages—inheritance: a form of software reusability in which new classes are
developed quickly and easily by absorbing the capabilities of existing classes
and adding appropriate new capabilities. In the context of an
Employee hierarchy case study,
this substantially revised chapter presents a five-example sequence
demonstrating private
data, protected
data and good software engineering with inheritance. We begin by demonstrating
a class with private
data members and public
member functions to manipulate that data. Next, we implement a second class
with additional capabilities, intentionally and tediously duplicating much of
the first example’s code. The third example begins our discussion of
inheritance and software reuse—we use the class from the first example as a
base class and quickly and simply inherit its data and functionality into a
new derived class. This example introduces the inheritance mechanism and
demonstrates that a derived class cannot access its base class’s
private members
directly. This motivates our fourth example, in which we introduce
protected data
in the base class and demonstrate that the derived class can indeed access the
protected data
inherited from the base class. The last example in the sequence demonstrates
proper software engineering by defining the base class’s data as
private and
using the base class’s public
member functions (that were inherited by the derived class) to manipulate the
base class’s private
data in the derived class. The chapter discusses the notions of base classes
and derived classes, protected
members, public
inheritance, protected
inheritance, private
inheritance, direct base classes, indirect base classes, constructors and
destructors in base classes and derived classes, and software engineering with
inheritance. The chapter also compares inheritance (the “is-a”
relationship) with composition (the “has-a”
relationship) and introduces the “uses-a” and “knows-a”
relationships.
Chapter 13—Object-Oriented Programming: Polymorphism—deals with
another fundamental capability of object-oriented programming: polymorphic
behavior. The completely revised Chapter 13 builds on the inheritance concepts
presented in Chapter 12 and focuses on the relationships among classes in a
class hierarchy and the powerful processing capabilities that these
relationships enable. When many classes are related to a common base class
through inheritance, each derived-class object may be treated as a base-class
object. This enables programs to be written in a simple and general manner
independent of the specific types of the derived-class objects. New kinds of
objects can be handled by the same program, thus making systems more
extensible. Polymorphism enables programs to eliminate complex
switch logic in favor of simpler “straight-line” logic. A
screen manager of a video game, for example, can send a
draw message to every object in a
linked list of objects to be drawn. Each object knows how to draw itself. An
object of a new class can be added to the program without modifying that
program (as long as that new object also knows how to draw itself). The
chapter discusses the mechanics of achieving polymorphic behavior via
virtual
functions. It distinguishes between abstract classes (from which objects
cannot be instantiated) and concrete classes (from which objects can be
instantiated). Abstract classes are useful for providing an inheritable
interface to classes throughout the hierarchy. We demonstrate abstract classes
and polymorphic behavior by revisiting the
Employee
hierarchy of Chapter 12. We introduce an abstract
Employee base class, from which
classes CommissionEmployee,
HourlyEmployee
and SalariedEmployee
inherit directly and class
BasePlusCommissionEmployee inherits indirectly. In the past,
our professional clients have insisted that we provide a deeper explanation
that shows precisely how polymorphism is implemented in C++, and hence,
precisely what execution time and memory “costs” are incurred when programming
with this powerful capability. We responded by developing an illustration and
a precise explanation of the vtables (virtual
function tables) that the C++ compiler builds automatically to support
polymorphism. To conclude, we introduce run-time type information (RTTI) and
dynamic casting, which enable a program to determine an object’s type at
execution time, then act on that object accordingly. Using RTTI and dynamic
casting, we give a 10% pay increase to employees of a specific type, then
calculate the earnings for such employees. For all other employee types, we
calculate their earnings polymorphically.
Chapter 14—Templates—discusses one of C++’s more powerful
software reuse features, namely templates. Function templates and class
templates enable programmers to specify, with a single code segment, an entire
range of related overloaded functions (called function template
specializations) or an entire range of related classes (called class-template
specializations). This technique is called generic programming. Function
templates were introduced in Chapter 6. This chapter presents additional
discussions and examples on function template. We might write a single class
template for a stack class, then have C++ generate separate class-template
specializations, such as a “stack-of-int”
class, a “stack-of-float”
class, a “stack-of-string”
class and so on. The chapter discusses using type parameters, nontype
parameters and default types for class templates. We also discuss the
relationships between templates and other C++ features, such as overloading,
inheritance, friends and
static members. The exercises challenge the student to write a
variety of function templates and class templates and to employ these in
complete programs. We greatly enhance the treatment of templates in our
discussion of the Standard Template Library (STL) containers, iterators and
algorithms in Chapter 23.
Chapter 15—C++
Stream Input/Output—contains a comprehensive treatment of
standard C++ input/output capabilities. This chapter discusses a range of
capabilities sufficient for performing most common I/O operations and
overviews the remaining capabilities. Many of the I/O features are object
oriented. This style of I/O makes use of other C++ features, such as
references, function overloading and operator overloading. The various I/O
capabilities of C++, including output with the stream insertion operator,
input with the stream extraction operator, type-safe I/O, formatted I/O,
unformatted I/O (for performance). Users can specify how to perform I/O for
objects of user-defined types by overloading the stream insertion operator (<<)
and the stream extraction operator (>>).
This extensibility is one of C++’s most valuable features. C++ provides
various stream manipulators that perform formatting tasks. This chapter
discusses stream manipulators that provide capabilities such as displaying
integers in various bases, controlling floating-point precision, setting field
widths, displaying decimal point and trailing zeros, justifying output,
setting and unsetting format state, setting the fill character in fields. We
also present an example that creates user-defined output stream
manipulators.
Chapter 16—Exception Handling—discusses how exception handling
enables programmers to write programs that are robust, fault tolerant and
appropriate for business-critical and mission-critical environments. The
chapter discusses when exception handling is appropriate; introduces the basic
capabilities of exception handling with
try blocks,
throw statements and
catch handlers;
indicates how and when to rethrow an exception; explains how to write an
exception specification and process unexpected exceptions; and discusses the
important ties between exceptions and constructors, destructors and
inheritance. The exercises in this chapter show the student the diversity and
power of C++’s exception-handling capabilities. We discuss rethrowing an
exception, and we illustrate how
new can fail when memory is
exhausted. Many older C++ compilers return 0 by default when
new fails. We show the new style
of new failing
by throwing a bad_alloc
(bad allocation) exception. We illustrate how to use function
set_new_handler
to specify a custom function to be called to deal with memory-exhaustion
situations. We discuss how to use the
auto_ptr class template to
delete
dynamically allocated memory implicitly, thus avoiding memory leaks. To
conclude this chapter, we present the Standard Library exception hierarchy.
Chapter 17—File
Processing—discusses techniques for creating and processing both
sequential files and random-access files. The chapter begins with an
introduction to the data hierarchy from bits, to bytes, to fields, to records
and to files. Next, we present the C++ view of files and streams. We discuss
sequential files and build programs that show how to open and close files, how
to store data sequentially in a file and how to read data sequentially from a
file. We then discuss random-access files and build programs that show how to
create a file for random access, how to read and write data to a file with
random access and how to read data sequentially from a randomly accessed file.
The case study combines the techniques of accessing files both sequentially
and randomly into a complete transaction-processing program. Students in our
industry seminars have mentioned that, after studying the material on file
processing, they were able to produce substantial file-processing programs
that were immediately useful in their organizations. The exercises ask the
student to implement a variety of programs that build and process both
sequential files and random-access files.
Chapter 18—Class
string
and String Stream Processing—The chapter discusses C++’s
capabilities for inputting data from strings in memory and outputting data to
strings in memory; these capabilities often are referred to as in-core
formatting or string-stream processing. Class
string is a required component of
the Standard Library. We preserved the treatment of C-like, pointer-based
strings in Chapter 8 and later for several reasons. First, it strengthens the
reader’s understanding of pointers. Second, for the next decade or so, C++
programmers will need to be able to read and modify the enormous amounts of C
legacy code that has accumulated over the last quarter of a century—this code
processes strings as pointers, as does a large portion of the C++ code that
has been written in industry over the last many years. In Chapter 18 we
discuss string
assignment, concatenation and comparison. We show how to determine various
string
characteristics such as a
string’s size, capacity and whether or not it is empty. We
discuss how to resize a string.
We consider the various “find” functions that enable us to find a substring in
a string
(searching the string
either forwards or backwards), and we show how to find either the first
occurrence or last occurrence of a character selected from a
string of characters, and how to
find the first occurrence or last occurrence of a character that is not in a
selected string of characters. We show how to replace, erase and
insert characters in a string
and how to convert a string
object to a C-style char
* string.
Chapter 19—Web
Programming—This optional chapter has everything you need to
begin developing your own Web-based applications that will really run on the
Internet! You will learn how to build so-called n-tier
applications, in which the functionality provided by each tier can be
distributed to separate computers across the Internet or executed on the same
computer. In particular, we build a three-tier online bookstore application.
The bookstore’s information is stored in the application’s bottom tier, also
called the data tier. In industrial-strength applications, the data tier is
typically a database such as Oracle, Microsoft
SQL Server or MySQL. For simplicity, we use text files and employ the
file-processing techniques of Chapter 17 to access and modify these files. The
user enters requests and receives responses at the application’s top tier,
also called the user-interface tier or the client tier, which is typically a
computer running a popular Web browser such as Microsoft Internet Explorer,
Mac OS X Safari
, Mozilla Firefox, Opera or Netscape .
Web browsers, of course, know how to communicate with Web sites throughout the
Internet. The middle tier, also called the business-logic tier, contains both
a Web server and an application-specific C++ program (e.g., our bookstore
application). The Web server communicates with the C++ program (and vice
versa) via the CGI (Common Gateway Interface) protocol. This program is
referred to as a CGI script. We use the popular Apache HTTP server, which is
available free for download from the Apache Web site,
www.apache.org. Apache installation instructions for many
popular platforms, including Linux and Windows systems, are available at that
site and at www.deitel.com
and www.prenhall.com/deitel.
The Web server knows how to talk to the client tier across the Internet using
a protocol called HTTP (Hypertext Transfer Protocol). We discuss the two most
popular HTTP methods for sending data to a Web server—GET
and POST. We
then discuss the crucial role of the Web server in Web programming and provide
a simple example that requests an
Extensible HyperText Markup Language
(XHTML)[1]
document from a Web server. We discuss CGI and how it allows a Web server to
communicate with the top tier and CGI applications. We provide a simple
example that gets the server’s time and renders it in a browser. Other
examples demonstrate how to process form-based user input via the string
processing techniques introduced in Chapter 18. In our forms-based examples we
use buttons, password fields, check boxes and text fields. We present an
example of an interactive portal for a travel company that displays airfares
to various cities. Travel-club members can log in and view discounted
airfares. We also discuss various methods of storing client-specific data,
which include hidden fields (i.e., information stored in a Web page but not
rendered by the Web browser) and
cookies—small text files that
the browser stores on the client’s machine. The chapter examples conclude with
a case study of an online book store that allows users to add books to a
shopping cart. This case study contains several CGI scripts that interact to
form a complete application. The online book store is password protected, so
users first must log in to gain access. The chapter’s Web resources include
information about the CGI specification, C++ CGI libraries and Web sites
related to the Apache HTTP server.
Chapter 20—Searching and Sorting—discusses two of the most
important classes of algorithms in computer science. We consider a variety of
specific algorithms for each and compare them with regard to their memory
consumption and processor consumption (introducing Big O notation, which
indicates how hard an algorithm may have to work to solve a problem).
Searching data involves determining whether a value (referred to as the search
key) is present in the data and, if so, finding the value’s location. In the
examples and exercises of this chapter, we discuss a variety of searching
algorithms, including: binary search and recursive versions of linear search
and binary search. Through examples and exercises, Chapter 20 discusses the
recursive merge sort, bubble sort, bucket sort and the recursive quicksort.
Chapter 21—Data
Structures—discusses the techniques used to create and
manipulate dynamic data structures. The chapter begins with discussions of
self-referential classes and dynamic memory allocation, then proceeds with a
discussion of how to create and maintain various dynamic data structures,
including linked lists, queues (or waiting lines), stacks and trees. For each
type of data structure, we present complete, working programs and show sample
outputs. The chapter also helps the student master pointers. The chapter
includes abundant examples that use indirection and double indirection—a
particularly difficult concept. One problem when working with pointers is
that students have trouble visualizing the data structures and how their nodes
are linked together. We have included illustrations that show the links and
the sequence in which they are created. The binary-tree example is a superb
capstone for the study of pointers and dynamic data structures. This example
creates a binary tree, enforces duplicate elimination and introduces
recursive preorder, inorder and postorder tree traversals. Students have a
genuine sense of accomplishment when they study and implement this example.
They particularly appreciate seeing that the inorder traversal prints the node
values in sorted order. We include a substantial collection of exercises. A
highlight of the exercises is the special section Building Your Own Compiler.
The exercises walk the student through the development of an
infix-to-postfix-conversion program and a postfix-expression-evaluation
program. We then modify the postfix-evaluation algorithm to generate
machine-language code. The compiler places this code in a file (using the
techniques of Chapter 17. Students then run the machine language produced by
their compilers on the software simulators they built in the exercises of
Chapter 8! The 35 exercises include recursively searching a list, recursively
printing a list backwards, binary-tree node deletion, level-order traversal of
a binary tree, printing trees, writing a portion of an optimizing compiler,
writing an interpreter, inserting/deleting anywhere in a linked list,
implementing lists and queues without tail pointers, analyzing the performance
of binary-tree searching and sorting, implementing an indexed-list class and
a supermarket simulation that uses queueing. After studying Chapter 21, the
reader is prepared for the treatment of STL containers, iterators and
algorithms in Chapter 23. The STL containers are prepackaged, templatized data
structures that most programmers will find sufficient for the vast majority of
applications they will need to implement. The STL is a giant leap forward in
achieving the vision of reuse.
Chapter 22—Bits, Characters, Strings and Structures—presents a
variety of important features. This chapter begins by comparing C++
structures to classes then defining and using C-like structures. We show how
to declare structures, initialize structures and pass structures to functions.
The chapter features a high-performance card-shuffling and dealing simulation.
This is an excellent opportunity for the instructor to emphasize the quality
of algorithms. C++’s powerful bit-manipulation capabilities enable programmers
to write programs that exercise lower-level hardware capabilities. This helps
programs process bit strings, set individual bits and store information more
compactly. Such capabilities, often found only in low-level assembly
languages, are valued by programmers writing system software, such as
operating systems and networking software. As you recall, we introduced
C-style char *
string manipulation in Chapter 8 and presented the most popular
string-manipulation functions. In Chapter 22, we continue our presentation of
characters and C-style char *
strings. We present the various character-manipulation capabilities of the
<cctype>
library—such as the ability to test a character to determine whether it is a
digit, an alphabetic character, an alphanumeric character, a hexadecimal
digit, a lowercase letter or an uppercase letter. We present the remaining
string-manipulation functions of the various string-related libraries; as
always, every function is presented in the context of a complete, working C++
program. The 32 exercises encourage the student to try out most of the
capabilities discussed in the chapter. The feature exercise leads the student
through the development of a spelling-checker program. This chapter presents a
deeper treatment of C-like,
char *
strings for the benefit of C++ programmers who are likely to work with C
legacy code.
Chapter 23—Standard Template Library (STL)—Throughout this book,
we discuss the importance of software reuse. Recognizing that many data
structures and algorithms are commonly used by C++ programmers, the C++
standard committee added the Standard Template Library (STL) to the C++
Standard Library. The STL defines powerful, template-based, reusable
components that implement many common data structures and algorithms used to
process those data structures. The STL offers proof of concept for generic
programming with templates—introduced in Chapter 14 and demonstrated in detail
in Chapter 21. This chapter introduces the STL and discusses its three key
components—containers (popular templatized data structures), iterators and
algorithms. The STL containers are data structures capable of storing objects
of any data type. We will see that there are three container
categories—first-class containers, adapters and near containers. STL iterators,
which have similar properties to those of pointers, are used by programs to
manipulate the STL-container elements. In fact, standard arrays can be
manipulated as STL containers, using standard pointers as iterators. We will
see that manipulating containers with iterators is convenient and provides
tremendous expressive power when combined with STL algorithms—in some cases,
reducing many lines of code to a single statement. STL algorithms are
functions that perform common data manipulations such as searching, sorting
and comparing elements (or entire containers). There are approximately 70
algorithms implemented in the STL. Most of these use iterators to access
container elements. We will see that each first-class container supports
specific iterator types, some of which are more powerful than others. A
container’s supported iterator type determines whether the container can be
used with a specific algorithm. Iterators encapsulate the mechanism used to
access container elements. This encapsulation enables many of the STL
algorithms to be applied to several containers without regard for the
underlying container implementation. As long as a container’s iterators
support the minimum requirements of the algorithm, then the algorithm can
process that container’s elements. This also enables programmers to create
algorithms that can process the elements of multiple different container
types. Chapter 21 discusses how to implement data structures with pointers,
classes and dynamic memory. Pointer-based code is complex, and the slightest
omission or oversight can lead to serious memory-access violations and
memory-leak errors with no compiler complaints. Implementing additional data
structures such as deques, priority queues, sets, maps, etc. requires
substantial additional work. In addition, if many programmers on a large
project implement similar containers and algorithms for different tasks, the
code becomes difficult to modify, maintain and debug. An advantage of the STL
is that programmers can reuse the STL containers, iterators and algorithms to
implement common data representations and manipulations. This reuse results in
substantial development-time and resource savings. This is a friendly,
accessible chapter that should convince you of the value of the STL and
encourage further study.
Chapter 24—Other Topics—is a collection of miscellaneous C++
topics. This chapter discusses one additional cast operator—const_cast.
This operator, along with
static_cast (Chapter 5),
dynamic_cast (Chapter 13) and
reinterpret_cast
(Chapter 17), provide a more robust mechanism for converting between types
than do the original cast operators C++ inherited from C (which are now
deprecated). We discuss namespaces, a feature particularly crucial for
software developers who build substantial systems, especially for those who
build systems from class libraries. Namespaces prevent naming collisions,
which can hinder such large software efforts. The Chapter discusses the
operator keywords, which are useful for programmers who have keyboards that do
not support certain characters used in operator symbols, such as
!,
&,
^,
~ and
|. These
operators can also be used by programmers who do not like cryptic operator
symbols. We discuss keyword
mutable, which allows a member of a
const object to be changed.
Previously, this was accomplished by “casting away
const-ness”, which is considered a
dangerous practice. We also discuss pointer-to-member operators
.* and
->*, multiple
inheritance (including the problem of “diamond inheritance”) and
virtual base
classes.
Appendix A—Operator Precedence and Associativity Chart—presents
the complete set of C++ operator symbols, in which each operator appears on a
line by itself with its operator symbol, its name and its associativity.
Appendix B—ASCII Character Set—All the programs in this book use
the ASCII character set, which is presented in this appendix.
Appendix C—Fundamental
Types—lists all fundamental types defined in the
C++ Standard.
Appendix D—Number Systems—discusses the binary, octal, decimal
and hexadecimal number systems. It considers how to convert numbers between
bases and explains the one’s complement and two’s complement binary
representations.
Appendix E—C
Legacy-Code Topics—presents additional topics including several
advanced topics not ordinarily covered in introductory courses. We show how to
redirect program input to come from a file, redirect program output to be
placed in a file, redirect the output of one program to be the input of
another program (piping) and append the output of a program to an existing
file. We develop functions that use variable-length argument lists and show
how to pass command-line arguments to function
main and use them in a program. We
discuss how to compile programs whose components are spread across multiple
files, register functions with
atexit to be executed at program
termination and terminate program execution with function
exit. We also discuss the
const and
volatile type
qualifiers, specifying the type of a numeric constant using the integer and
floating-point suffixes, using the signal-handling library to trap unexpected
events, creating and using dynamic arrays with
calloc and
realloc, using
unions as a space-saving technique
and using linkage specifications when C++ programs are to be linked with
legacy C code. As the title suggests, this chapter is intended primarily for
C++ programmers who will be working with C legacy code as most C++ programmers
are almost certain to do at one point in their careers.
Appendix F—Preprocessor—provides detailed discussions of the
preprocessor directives. The chapter includes more complete information on
the #include
directive, which causes a copy of a specified file to be included in place of
the directive before the file is compiled and the
#define directive that creates
symbolic constants and macros. The chapter explains conditional compilation
for enabling the programmer to control the execution of preprocessor
directives and the compilation of program code. The
# operator that converts its
operand to a string and the ##
operator that concatenates two tokens are discussed. The various predefined
preprocessor symbolic constants (__LINE__,
__FILE__,
__DATE__,
__STDC__,
__TIME__ and
__TIMESTAMP__)
are presented. Finally, macro
assert of the header file
<cassert> is discussed, which is
valuable in program testing, debugging, verification and validation.
Appendix G—ATM
Case Study Code—contains the implementation of our case
study on object-oriented design with the UML. This appendix is discussed in
the overview of the case study (presented shortly).
Appendix H—UML
2 Diagrams—Overviews the UML 2 diagram types that are not found
in the OOD/UML Case Study.
Appendix I—C++
Internet and Web Resources—contains a listing of valuable C++
resources, such as demos, information about popular compilers (including
“freebies”), books, articles, conferences, job banks, journals, magazines,
help, tutorials, FAQs (frequently asked questions), newsgroups, Web-based
courses, product news and C++ development tools.
Appendix J—Introduction to XHTML—provides an introduction to
XHTML—a markup language for describing the elements of a Web page so that a
browser, such as Microsoft Internet Explorer or Netscape, can render that
page. The reader should be familiar with the contents of this appendix before
studying Chapter 16, Web Programming with CGI. This appendix does not contain
any C++ programming. Some key topics covered include incorporating text and
images into an XHTML document, linking to other XHTML documents, incorporating
special characters (such as copyright and trademark symbols) into an XHTML
document, separating parts of an XHTML document with horizontal lines (called
horizontal rules), presenting information in
lists and
tables, and collecting
information from users browsing a site.
Appendix K—XHTML
Special Characters—lists many commonly used XHTML special
characters, called character entity references.
Appendix L—Using
the Visual C++ .NET Debugger—demonstrates key features of the Visual
Studio .NET Debugger, which allows a programmer to monitor the execution of
applications to locate and remove logic errors. The appendix presents
step-by-step instructions, so students learn how to use the debugger in a
hands-on manner.
Appendix M—Using
the GNU C++ Debugger—demonstrates key features of the GNU C++ Debugger,
which allows a programmer to monitor the execution of applications to locate
and remove logic errors. The appendix presents step-by-step instructions, so
students learn how to use the debugger in a hands-on manner.
Bibliography—lists
over 100 books and articles to encourage the student to do further reading on
C++ and OOP.
Index—The
comprehensive index enables the reader to locate by keyword any term or
concept throughout the text.
Object-Oriented Design of an ATM with the UML:
A
Tour of the Optional Software Engineering Case Study
In this section we tour the book’s
optional case study of object-oriented design with the UML. This tour previews
the contents of the nine Software Engineering Case Study sections (in
Chapters 1–7, 9 and 13). After completing this case study, the reader will be
thoroughly familiar with a carefully reviewed obj |