Instant Download Ebook of Brief C Late Objects 3Rd Edition Cay Horstmann Online Full Chapter PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

Brief C Late Objects 3rd Edition Cay

Horstmann
Visit to download the full and correct content document:
https://ebookmeta.com/product/brief-c-late-objects-3rd-edition-cay-horstmann/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Big C late objects 3rd Edition Cay S. Horstmann

https://ebookmeta.com/product/big-c-late-objects-3rd-edition-cay-
s-horstmann/

Java For Everyone Late Objects Cay S Horstmann

https://ebookmeta.com/product/java-for-everyone-late-objects-cay-
s-horstmann/

Big Java Late Objects Enhanced eText 2nd Edition Cay S.


Horstmann

https://ebookmeta.com/product/big-java-late-objects-enhanced-
etext-2nd-edition-cay-s-horstmann/

Core Java for the Impatient 3rd Edition Cay Horstmann

https://ebookmeta.com/product/core-java-for-the-impatient-3rd-
edition-cay-horstmann/
Core Java Volume II Advanced Features Cay S Horstmann

https://ebookmeta.com/product/core-java-volume-ii-advanced-
features-cay-s-horstmann/

Modern JavaScript for the Impatient 1st Edition Cay S.


Horstmann

https://ebookmeta.com/product/modern-javascript-for-the-
impatient-1st-edition-cay-s-horstmann/

Core Java, Vol. II-Advanced Feature 12th Edition Cay S.


Horstmann

https://ebookmeta.com/product/core-java-vol-ii-advanced-
feature-12th-edition-cay-s-horstmann/

C++20 for Programmers: An Objects-Natural Approach 3rd


Edition Paul Deitel

https://ebookmeta.com/product/c20-for-programmers-an-objects-
natural-approach-3rd-edition-paul-deitel/

Java How to Program, Late Objects, Global Edition


Harvey Deitel

https://ebookmeta.com/product/java-how-to-program-late-objects-
global-edition-harvey-deitel/
BriefC++
Cay Horstmann

Late Objects
3/e
BriefC++
Late Objects
3/e
BriefC++ Late Objects
3/e

Cay Horstmann
San Jose State University
PUBLISHER Laurie Rosatone
EDITORIAL DIRECTOR Don Fowley
DEVELOPMENTAL EDITOR Cindy Johnson
ASSISTANT DEVELOPMENT EDITOR Ryann Dannelly
EXECUTIVE MARKETING MANAGER Dan Sayre
SENIOR PRODUCTION EDITOR Laura Abrams
SENIOR CONTENT MANAGER Valerie Zaborski
EDITORIAL ASSISTANT Anna Pham
SENIOR DESIGNER Tom Nery
SENIOR PHOTO EDITOR Billy Ray
PRODUCTION MANAGEMENT Cindy Johnson
COVER IMAGE © Monty Rakusen/Getty Images

This book was set in Stempel Garamond LT Std by Publishing Services, and printed and bound by Quad/
Graphics, Versailles. The cover was printed by Quad/Graphics, Versailles.

This book is printed on acid-free paper. ∞

Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more
than 200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is
built on a foundation of principles that include responsibility to the communities we serve and where we live
and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental,
social, economic, and ethical challenges we face in our business. Among the issues we are addressing are carbon
impact, paper specifications and procurement, ethical conduct within our business and among our vendors,
and community and charitable support. For more information, please visit our website: www.wiley.com/go/
citizenship.

Copyright © 2018, 2012, 2009 John Wiley & Sons, Inc. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by
any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under
Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of
the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance
Center, Inc. 222 Rosewood Drive, Danvers, MA 01923, website www.copyright.com. Requests to the Publisher
for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street,
Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008, website http://www.wiley.com/go/permissions.

Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to a
third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc-
tions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. If you have
chosen to adopt this textbook for use in your course, please accept this book as your complimentary desk copy.
Outside of the United States, please contact your local representative.

ISBN 13: 978-1-119-40042-4

The inside back cover will contain printing identification and country of origin if omitted from this page. In
addition, if the ISBN on the back cover differs from the ISBN on this page, the one on the back cover is correct.

Printed in the United States of America.

10 9 8 7 6 5 4 3 2 1
P R E FA C E

This book is an introduction to C++ and computer programming that focuses on


the essentials—and on effective learning. The book is designed to serve a wide range
of student interests and abilities and is suitable for a first course in programming for
computer scientists, engineers, and students in other disciplines. No prior program-
ming experience is required, and only a modest amount of high school algebra is
needed.
Here are the key features of this book:

Present fundamentals first.


This book uses the C++ programming language as a vehicle for introducing com-
puter science concepts. A substantial subset of the C++ language is covered, focusing
on the modern features of standard C++ that make students productive. The book
takes a traditional route, first stressing control structures, procedural decomposition,
and array algorithms. Objects are used when appropriate in the early chapters. Stu-
dents start designing and implementing their own classes in Chapter 9.

Guidance and worked examples help students succeed.


Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc-
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “Problem Solving” sections stress the
importance of design and planning. “How To” guides help students with common
programming tasks. Additional Worked Examples are available in the E-Text or
online.
Tip: Source files for all of the program examples in the book, including the Worked
Examples, are provided with the source code for this book. Download the files to
your computer for easy access as you work through the chapters.
Practice makes perfect.
Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. The Enhanced E-Text
immerses students in activities designed to foster in-depth learning. Students don’t
just watch animations and code traces, they work on generating them. The activities
provide instant feedback to show students what they did right and where they need
to study more. A wealth of practice opportunities, including code completion ques-
tions and skill-oriented multiple-choice questions, appear at the end of each section,
and each chapter ends with well-crafted review exercises and programming projects.
Problem solving strategies are made explicit.
Practical, step-by-step illustrations of techniques help students devise and evaluate
solutions to programming problems. Introduced where they are most relevant, these
strategies address barriers to success for many students. Strategies included are:
• Algorithm Design (with pseudocode)
• First Do It By Hand (doing sample calculations by hand)
• Flowcharts

v
vi Preface

• Selecting Test Cases


• Hand-Tracing
• Storyboards
• Solve a Simpler Problem First
• Reusable Functions
• Stepwise Refinement
• Adapting Algorithms
• Discovering Algorithms by Manipulating Physical Objects
• Draw a Picture (pointer diagrams)
• Tracing Objects (identifying state and behavior)
• Discovering Classes
A visual approach motivates the reader and eases navigation.
Photographs present visual analogies that explain
the nature and behavior of computer concepts.
Step-by-step figures illustrate complex program
operations. Syntax boxes and example tables pres-
ent a variety of typical and special cases in a com-
pact format. It is easy to get the “lay of the land” by
browsing the visuals, before focusing on the textual
material.
Focus on the essentials while being
© Terraxplorer/iStockphoto.
technically accurate.
An encyclopedic coverage is not helpful for a Visual features help the reader
beginning programmer, but neither is the oppo- with navigation.
site—reducing the material to a list of simplistic
bullet points. In this book, the essentials are presented in digestible chunks, with sep-
arate notes that go deeper into good practices or language features when the reader is
ready for the additional information. You will not find artificial over-simplifications
that give an illusion of knowledge.
Reinforce sound engineering practices.
A multitude of useful tips on software quality and common errors encourage the
development of good programming habits. The focus is on test-driven development,
encouraging students to test their programs systematically.
Engage with optional engineering and business exercises.
End-of-chapter exercises are enhanced with problems from scientific and business
domains. Designed to engage students, the exercises illustrate the value of program-
ming in applied fields.
Preface vii

New to This Edition


Updated for Modern Versions of C++
A number of features of the C++ 2011 and C++ 2014 standards are described either as
recommended “best practice” or as Special Topics.

New and Reorganized Topics


The book now supports two pathways into object-oriented programming and inher-
itance. Pointers and structures can be covered before introducing classes. Alterna-
tively, pointers can be deferred until after the implementation of classes.
A sequence of Worked Examples and exercises introduces “media computa-
tion”—generating and modifying images, sounds, and animations.

Lower-Cost, Interactive Format


This third edition is published as a lower-cost Enhanced E-Text that supports active
learning through a wealth of interactive activities. These activities engage and prepare
students for independent programming and the Review Exercises, Practice Exercises,
and Programming Projects at the end of each E-Text chapter. The Enhanced E-Text
may also be bundled with an Abridged Print Companion, which is a bound book that
contains the entire text for reference, but without exercises or practice material.
Interactive learning solutions are expanding every day, so to learn more about
these options or to explore other options to suit your needs, please contact your
Wiley account manager (www.wiley.com/go/whosmyrep) or visit the product information
page for this text on wiley.com (http://wiley.com/college/sc/horstmann).
The Enhanced E-Text is designed to enable student practice without the instructor
assigning the interactivities or recording their scores. If you are interested in assign-
ing and grading students’ work on them, ask your Wiley Account Manager about the
online course option implemented in the Engage Learning Management System. The
Engage course supports the assignment and automatic grading of the interactivities.
Engage access includes access to the Enhanced E-Text.

Features in the Enhanced E-Text


The interactive Enhanced E-Text guides students from the basics to writing complex
programs. After they read a bit, they can try all of the interactive exercises for that
section. Active reading is an engaging way for students to ensure that students are
prepared before going to class.
There five types of interactivities:
Code Walkthrough Code Walkthrough activities ask students to trace through a
segment of code, choosing which line will be executed next and entering the new
values of variables changed by the code’s execution. This activity simulates the hand-
tracing problem solving technique taught in Chapters 3 and 4—but with immediate
feedback.
viii Preface

Example Table Example table activities make the student the active participant in
building up tables of code examples similar to those found in the book. The tables
come in many different forms. Some tables ask the student to determine the output of
a line of code, or the value of an expression, or to provide code for certain tasks. This
activity helps students assess their understanding of the reading—while it is easy to
go back and review.
Algorithm Animation An algorithm animation shows the essential steps of an
algorithm. However, instead of passively watching, students get to predict each step.
When finished, students can start over with a different set of inputs. This is a surpris-
ingly effective way of learning and remembering algorithms.
Rearrange Code Rearrange code activities ask the student to arrange lines of code
by dragging them from the list on the right to the area at left so that the resulting code
fulfills the task described in the problem. This activity builds facility with coding
structure and implementing common algorithms.
Object Diagram Object diagram activities ask the student to create a memory
diagram to illustrate how variables and objects are initialized and updated as sample
code executes. The activity depicts variables, objects, and references in the same way
as the figures in the book. After an activity is completed, pressing “Play” replays the
animation. This activity goes beyond hand-tracing to illuminate what is happening in
memory as code executes.
Code Completion Code completion activities ask the student to finish a partially-
completed program, then paste the solution into CodeCheck (a Wiley-based online
code evaluator) to learn whether it produces the desired result. Tester classes on the
CodeCheck site run and report whether the code passed the tests. This activity serves
as a skill-building lab to better prepare the student for writing programs from scratch.

A Tour of the Book


This book is intended for a two-semester introduction to programming that may also
include algorithms and data structures. The organization of chapters offers the same
flexibility as the previous edition; dependencies among the chapters are also shown
in Figure 1.

Part A: Fundamentals (Chapters 1–8)


The first six chapters follow a traditional approach to basic programming concepts.
Students learn about control structures, stepwise refinement, and arrays. Objects are
used only for input/output and string processing. Input/output is first covered in
Chapter 2, which may be followed by an introduction to reading and writing text
files in Section 8.1.
In a course for engineers with a need for systems and embedded programming,
you will want to cover Chapter 7 on pointers. Sections 7.1 and 7.4 are sufficient for
using pointers with polymorphism in Chapter 10.
File processing is the subject of Chapter 8. Section 8.1 can be covered sooner for
an introduction to reading and writing text files. The remainder of the chapter gives
additional material for practical applications.
Preface ix

Part B: Object-Oriented Design (Chapters 9–10)


After students have gained a solid foundation, they are ready to tackle the implemen-
tation of classes. Chapters 9 and 10 introduce the object-oriented features of C++.
Chapter 9 introduces class design and implementation. Chapter 10 covers inheritance
and polymorphism. By the end of these chapters, students will be able to implement
programs with multiple interacting classes.
Any subset of these chapters can be incorporated into a custom print version of
this text; ask your Wiley sales representative for details, or visit customselect.wiley.com
to create your custom order.

Appendices
Appendices A and B summarize C++ reserved words and operators. Appendix C
lists character escape sequences and ASCII character code values. Appendix D docu-
ments all of the library functions and classes used in this book.
Appendix E contains a programming style guide. Using a style guide for program-
ming assignments benefits students by directing them toward good habits and reduc-
ing gratuitous choice. The style guide is available in electronic form on the book’s
companion web site so that instructors can modify it to reflect their preferred style.
Appendix F, available in the E-Text, introduces common number systems used in
computing.

Fundamentals
1. Introduction
Object-Oriented Design

2. Fundamental
Data Types

3. Decisions

4. Loops

A gentle
introduction to recursion
5. Functions is optional.
Section 8.1
contains the core
material
6. Arrays
6. Iteration
and Vectors

7. Pointers 8. Streams 9. Classes

Sections 10. Inheritance


7.1 and 7.4 are
required

Figure 1 Chapter Dependencies


x Preface

Web Resources
This book is complemented by a complete suite of online resources. Go to www.wiley.
com/go/bclo3 to visit the online companion sites, which include

• Source code for all example programs in the book and its Worked Examples, plus
additional example programs.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Lecture presentation slides (for instructors only).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only). This
extensive set of multiple-choice questions can be used with a word processor or
imported into a course management system.
• “CodeCheck” assignments that allow students to work on programming prob-
lems presented in an innovative online service and receive immediate feedback.
Instructors can assign exercises that have already been prepared, or easily add
their own. Visit http://codecheck.it to learn more.

Pointers in the print


companion describe what
students will find in their WORKED EXAMPLE 2.1
Computing Travel Time
E-Text or online.
Learn how to develop a hand calculation to compute the time that
a robot requires to retrieve an item from rocky terrain. See your
.
E-Text or visit wiley.com/go/bclo3
Courtesy of NASA.

EXAMPLE CODE See how_to_1/scores_vector in your companion code for a solution using vectors instead of arrays.
Walkthrough xi

A Walkthrough of the Learning Aids


The pedagogical elements in this book work together to focus on and reinforce key
concepts and fundamental principles of programming, with additional tips and detail
organized to support and deepen these fundamentals. In addition to traditional
features, such as chapter objectives and a wealth of exercises, each chapter contains
elements geared to today’s visual learner.

106 Chapter 4 Loops

4.3 The for Loop


Throughout each chapter,
It often happens that you want to execute a sequence of
margin notes show where The for loop is
used when a statements a given number of times. You can use a while
value runs from a loop that is controlled by a counter, as in the following
new concepts are introduced starting point to an
ending point with a
example:
and provide an outline of key ideas. constant increment
or decrement.
counter = 1; // Initialize the counter
while (counter <= 10) // Check the counter
{
cout << counter << endl;
counter++; // Update the counter
}

Because this loop type is so common, there is a special


form for it, called the for loop (see Syntax 4.2).
for (counter = 1; counter <= 10; counter++)
{
© Enrico Fianchini/iStockphoto.
cout << counter << endl;
}
You can visualize the
Some people call this loop count-controlled. In contrast, for loop as an orderly
the while loop of the preceding section can be called an sequence of steps.
event-controlled loop because it executes until an event
occurs (for example, when the balance reaches the target). Another commonly-used
Annotated syntax boxes term for a count-controlled loop is definite. You know from the outset that the loop
body will be executed a definite number of times––ten times in our example. In con-
provide a quick, visual overview trast, you do not know how many iterations it takes to accumulate a target balance.
Such a loop is called indefinite.
of new language constructs.
Syntax 4.2 for Statement

These three
expressions should be related.
See Programming Tip 4.1.

Annotations explain This initialization The loop is This update is


required components happens once
before the loop starts.
executed while
this condition is true.
executed after
each iteration.
and point to more information for (int i = 5; i <= 10; i++)

on common errors or best practices The variable i is


{
sum = sum + i;
This loop executes 6 times.
associated with the syntax. defined only in this
for loop.
}
See Programming Tip 4.3.

The for loop neatly groups the initialization, condition, and update expressions
together. However, it is important to realize that these expressions are not executed
together (see Figure 3).

Analogies to everyday objects are


used to explain the nature and behavior
of concepts such as variables, data
Like a variable in a computer types, loops, and more.
program, a parking space has
an identifier and contents.
xii Walkthrough

Memorable photos reinforce


analogies and help students
remember the concepts. pie(fruit) pie(fruit)

A recipe for a fruit pie may say to use any kind of fruit.
Here, “fruit” is an example of a parameter variable.
Apples and cherries are examples of arguments.

Problem Solving sections teach


techniques for generating ideas and
6.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 277
evaluating proposed solutions, often
using pencil and paper or other Now how does that help us with our problem, switching the first and the second
half of the array?
artifacts. These sections emphasize Let’s put the first coin into place, by swapping it with the fifth coin. However, as
C++ programmers, we will say that we swap the coins in positions 0 and 4:
that most of the planning and problem
solving that makes students successful
happens away from the computer.

Next, we swap the coins in positions 1 and 5:

HOW TO 1.1
Describing an Algorithm with Pseudocode
This is the first of many “How To” sections in this book that give you step-by-step proce-
dures for carrying out important tasks in developing computer programs.
Before you are ready to write a program in C++, you need to develop an algorithm—a
method for arriving at a solution for a particular problem. Describe the algorithm in pseudo-
code––a sequence of precise steps formulated in English. To illustrate, we’ll devise an algo-
rithm for this problem:
How To guides give step-by-step
Problem Statement You have the choice of buying one guidance for common programming
of two cars. One is more fuel efficient than the other, but also
more expensive. You know the price and fuel efficiency (in miles tasks, emphasizing planning and
per gallon, mpg) of both cars. You plan to keep the car for ten
years. Assume a price of $4 per gallon of gas and usage of 15,000 testing. They answer the beginner’s
miles per year. You will pay cash for the car and not worry about
financing costs. Which car is the better deal? © dlewis33/Getty Images. question, “Now what do I do?” and
Step 1 Determine the inputs and outputs. integrate key concepts into a
In our sample problem, we have these inputs: problem-solving sequence.
• purchase price1 and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car
• purchase price2 and fuel efficiency2, the price and fuel efficiency of the second car

WORKED EXAMPLE 1.1


Writing an Algorithm for Tiling a Floor

Problem Statement Your task is to tile a rectangular bathroom floor with alternating Worked Examples apply
black and white tiles measuring 4 × 4 inches. The floor dimensions, measured in inches, are
multiples of 4. the steps in the How To to
Step 1 Determine the inputs and outputs.
a different example, showing
The inputs are the floor dimensions (length × width), how they can be used to
measured in inches. The output is a tiled floor.
Step 2 Break down the problem into smaller tasks.
plan, implement, and test
A natural subtask is to lay one row of tiles. If you can a solution to another
solve that task, then you can solve the problem by lay-
ing one row next to the other, starting from a wall, until programming problem.
you reach the opposite wall.
How do you lay a row? Start with a tile at one wall.
If it is Names
Table 3 Variable white, putin
a black
C++ one next to it. If it is black, put
a white one next to it. Keep going until you reach the
Variable Name wall. The row will contain width / 4 tiles.
opposite Comment © rban/iStockphoto.

Step 3 Describe each subtask in pseudocode.


can_volume1 Variable names consist of letters, numbers, and the underscore
character.
x In mathematics, you use short variable names such as x or y. This is
legal in C++, but not very common, because it can make programs
harder to understand (see Programming Tip 2.1). Example tables support beginners
!
Can_volume Caution: Variable names are case sensitive. This variable name is with multiple, concrete examples.
different from can_volume.
These tables point out common
6pack Error: Variable names cannot start with a number.

can volume Error: Variable names cannot contain spaces.


errors and present another quick
double Error: You cannot use a reserved word as a variable name. reference to the section’s topic.
ltr/fl.oz Error: You cannot use symbols such as . or /
Walkthrough xiii

Consider the function call illustrated in Figure 3:


double result1 = cube_volume(2); Progressive figures trace code
• The parameter variable side_length of the cube_volume function is created. ❶
• The parameter variable is initialized with the value of the argument that was
segments to help students visualize
passed in the call. In our case, side_length is set to 2. ❷ the program flow. Color is used
• The function computes the expression side_length * side_length * side_length,
which has the value 8. That value is stored in the variable volume. ❸ consistently to make variables and
• The function returns. All of its variables are removed. The return value is trans-
ferred to the caller, that is, the function calling the cube_volume function. ❹
other elements easily recognizable.

1 Function call result1 =


double result1 = cube_volume(2);

1 Initialize counter
side_length = for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
2 Initializing function parameter variable counter = 1 }
result1 =
double result1 = cube_volume(2);
2 Check condition
side_length = for (counter = 1; counter <= 10; counter++)
2
{
cout << counter << endl;
counter = 1 }
3 About to return to the caller result1 =

3 Execute loop body


for (counter = 1; counter <= 10; counter++)
side_length = 2 {
double volume = side_length * side_length * side_length;
return volume; cout << counter << endl;
volume = 8 counter = 1 }

4 After function call result1 = 8 4 Update counter


for (counter = 1; counter <= 10; counter++)
double result1 = cube_volume(2); {
cout << counter << endl;
counter = 2 }
Figure 3 Parameter Passing

5 Check condition again


for (counter = 1; counter <= 10; counter++)
{
cout << counter << endl;
counter = 2 }

Figure 3 Execution of a for Loop


Optional engineering exercises
engage students with applications
from technical fields. Engineering P7.12 Write a program that simulates the control
software for a “people mover” system, a set of
driverless trains that move in two concentric
circular tracks. A set of switches allows trains
to switch tracks.
In your program, the outer and inner tracks
should each be divided into ten segments.
Each track segment can contain a train that
moves either clockwise or counterclockwise.
sec02/cube.cpp A train moves to an adjacent segment in its track or, if that segment is occupied, to
the adjacent segment in the other track.
1 #include <iostream>
2 Define a Segment structure. Each segment has a pointer to the next and previous
3 using namespace std; segments in its track, a pointer to the next and previous segments in the other track,
4
5 /**
6 Computes the volume of a cube.
7 @param side_length the side length of the cube
8 @return the volume
9 */
10 double cube_volume(double side_length)
11 {
12 double volume = side_length * side_length * side_length;
13 return volume;
14 }
15
16 int main()
Program listings are carefully
17
18
{
double result1 = cube_volume(2); designed for easy reading,
double result2 = cube_volume(10);
19
20 cout << "A cube with side length 2 has volume " << result1 << endl; going well beyond simple
21 cout << "A cube with side length 10 has volume " << result2 << endl;
22 color coding. Functions are set
23 return 0;
24 } off by a subtle outline.
Program Run
A cube with side length 2 has volume 8
A cube with side length 10 has volume 1000

EXAMPLE CODE See sec04 of your companion code for another implementation of the earthquake program that you
Additional example programs
saw in Section 3.3. Note that the get_description function has multiple return statements.
are provided with the companion
code for students to read, run,
and modify.
xiv Walkthrough

Common Errors describe the kinds Common Error 2.1


Using Undefined Variables
of errors that students often make, You must define a variable before you use it for the first time. For example, the following
with an explanation of why the errors sequence of statements would not be legal:
double can_volume = 12 * liter_per_ounce;
occur, and what to do about them. double liter_per_ounce = 0.0296;
In your program, the statements are compiled in order. When the compiler reaches the first
statement, it does not know that liter_per_ounce will be defined in the next line, and it reports
an error.

Programming Tip 3.6


Hand-Tracing
A very useful technique for understanding whether a program
works correctly is called hand-tracing. You simulate the pro-
gram’s activity on a sheet of paper. You can use this method with
pseudocode or C++ code.
Get an index card, a cocktail napkin, or whatever sheet of
Programming Tips explain paper is within reach. Make a column for each variable. Have the
program code ready. Use a marker, such as a paper clip, to mark
good programming practices, the current statement. In your mind, execute statements one at a
time. Every time the value of a variable changes, cross out the old
and encourage students to be value and write the new value below the old one.
© thomasd007/iStockphoto.

For example, let’s trace the tax program with the data from the
more productive with tips and program run in Section 3.4. In lines 13 and 14, tax1 and tax2 are
Hand-tracing helps you
understand whether a
initialized to 0. program works correctly.
techniques such as hand-tracing. 6 int main()
7 {
8 const double RATE1 = 0.10; marital
9 const double RATE2 = 0.25; tax1 tax2 income status
10 const double RATE1_SINGLE_LIMIT = 32000;
11 const double RATE1_MARRIED_LIMIT = 64000; 0 0
12
13 double tax1 = 0;
14 double tax2 = 0;
15

In lines 18 and 22, income and marital_status are initialized by input statements.
16 double income;
17 cout << "Please enter your income: ";
18 cin >> income; marital
19 tax1 tax2 income status
20 cout << "Please enter s for single, m for married: ";
21 string marital_status; 0 0 80000 m
22 cin >> marital_status;
23

Because marital_status is not "s", we move to the else


branch of the outer if statement (line 36).
24 if (marital_status == "s")
25 {
26 if (income <= RATE1_SINGLE_LIMIT)
27
28
{ Special Topic 6.5
tax1 = RATE1 * income;
29
30
}
else The Range-Based for Loop
31 {
32 C++ 11 introduces a convenient syntax for visiting all elements in a “range” or sequence of ele-
tax1 = RATE1 * RATE1_SINGLE_LIMIT;
ments. This loop displays all elements in a vector:
vector<int> values = {1, 4, 9, 16, 25, 36};
for (int v : values)
{
cout << v << " ";
}

Special Topics present optional In each iteration of the loop, v is set to an element of the vector. Note that you do not use an
index variable. The value of v is the element, not the index of the element.
topics and provide additional If you want to modify elements, declare the loop variable as a reference:
for (int& v : values)
explanation of others. {
v++;
}
This loop increments all elements of the vector.
You can use the reserved word auto, which was introduced in Special Topic 2.3, for the type
of the element variable:
for (auto v : values) { cout << v << " "; }
The range-based for loop also works for arrays:
int primes[] = { 2, 3, 5, 7, 11, 13 };
for (int p : primes)
{
cout << p << " ";
}
Computing & Society 7.1 Embedded Systems The range-based for loop is a convenient shortcut for visiting or updating all elements of a
vector or an array. This book doesn’t use it because one can achieve the same result by looping
An embedded sys- would feel comfortable upgrading the duced in large volumes. Thus, the pro-
tem is a computer software in their washing machines grammer of an embedded system has
over index values. But if you like the more concise form, and use C++ 11 or later, you should
system that controls a device. The or automobile engines. If you ever a much larger economic incentive to certainly consider using it.
device contains a processor and other handed in a programming assignment conserve resources than the desktop
EXAMPLE CODE See special_topic_5 of your companion code for a program that demonstrates the range-based
hardware and is controlled by a com- that you believed to be correct, only to software programmer. Unfortunately, for loop.
puter program. Unlike a personal have the instructor or grader find bugs trying to conserve resources usually
computer, which has been designed in it, then you know how hard it is to makes it harder to write programs that
to be flexible and run many different write software that can reliably do its work correctly.
computer programs, the hardware task for many years without a chance C and C++ are commonly used
and software of an embedded system of changing it. Quality standards are languages for developing embedded
are tailored to a specific device. Com- especially important in devices whose systems.
puter controlled devices are becom- failure would destroy property or
ing increasingly common, ranging endanger human life. Many personal
from washing machines to medical computer purchasers buy computers Computing & Society presents social
equipment, cell phones, automobile that are fast and have a lot of stor-
engines, and spacecraft.
Several challenges are specific to
age, because the investment is paid
back over time when many programs
and historical topics on computing—for
programming embedded systems.
Most importantly, a much higher stan-
are run on the same equipment. But
the hardware for an embedded device
interest and to fulfill the “historical and
dard of quality control applies. Ven-
dors are often unconcerned about
is not shared––it is dedicated to one
device. A separate processor, memory,
social context” requirements of the
bugs in personal computer software,
because they can always make you
and so on, are built for every copy of
the device. If it is possible to shave a ACM/IEEE curriculum guidelines.
install a patch or upgrade to the next few pennies off the manufacturing © Courtesy of Professor Prabal Dutta.
version. But in an embedded system, cost of every unit, the savings can add
that is not an option. Few consumers up quickly for devices that are pro- The Controller of an Embedded System
Walkthrough xv

Interactive activities in the E-Text


engage students in active reading as they…

Trace through a code segment

Build an example table

Explore common algorithms

Arrange code to fulfill a task

Complete a program and Create a memory diagram


get immediate feedback
Acknowledgments xvii

Acknowledgments
Many thanks to Don Fowley, Graig Donini, Dan Sayre, Ryann Dannelly, David
Dietz, Laura Abrams, and Billy Ray at John Wiley & Sons for their help with this
project. An especially deep acknowledgment and thanks goes to Cindy Johnson for
her hard work, sound judgment, and amazing attention to detail.
I am grateful to Mark Atkins, Ivy Technical College, Katie Livsie, Gaston College,
Larry Morell, Arkansas Tech University, and Rama Olson, Gaston College, for
their contributions to the supplemental material. Special thanks to Stephen Gilbert,
Orange Coast Community College, for his help with the interactive exercises.
Every new edition builds on the suggestions and experiences of new and prior
reviewers, contributors, and users. We are very grateful to the individuals who pro-
vided feedback, reviewed the manuscript, made valuable suggestions and contribu-
tions, and brought errors and omissions to my attention. They include:
Charles D. Allison, Utah Valley State College
Fred Annexstein, University of Cincinnati
Mark Atkins, Ivy Technical College
Stefano Basagni, Northeastern University
Noah D. Barnette, Virginia Tech
Susan Bickford, Tallahassee Community College
Ronald D. Bowman, University of Alabama, Huntsville
Robert Burton, Brigham Young University
Peter Breznay, University of Wisconsin, Green Bay
Richard Cacace, Pensacola Junior College, Pensacola
Kuang-Nan Chang, Eastern Kentucky University
Joseph DeLibero, Arizona State University
Subramaniam Dharmarajan, Arizona State University
Mary Dorf, University of Michigan
Marty Dulberg, North Carolina State University
William E. Duncan, Louisiana State University
John Estell, Ohio Northern University
Waleed Farag, Indiana University of Pennsylvania
Evan Gallagher, Polytechnic Institute of New York University
Stephen Gilbert, Orange Coast Community College
Kenneth Gitlitz, New Hampshire Technical Institute
Daniel Grigoletti, DeVry Institute of Technology, Tinley Park
Barbara Guillott, Louisiana State University
Charles Halsey, Richland College
Jon Hanrath, Illinois Institute of Technology
Neil Harrison, Utah Valley University
Jurgen Hecht, University of Ontario
Steve Hodges, Cabrillo College
xviii Acknowledgments

Jackie Jarboe, Boise State University


Debbie Kaneko, Old Dominion University
Mir Behrad Khamesee, University of Waterloo
Sung-Sik Kwon, North Carolina Central University
Lorrie Lehman, University of North Carolina, Charlotte
Cynthia Lester, Tuskegee University
Yanjun Li, Fordham University
W. James MacLean, University of Toronto
LindaLee Massoud, Mott Community College
Adelaida Medlock, Drexel University
Charles W. Mellard, DeVry Institute of Technology, Irving
Larry Morell, Arkansas Tech University
Ethan V. Munson, University of Wisconsin, Milwaukee
Arun Ravindran, University of North Carolina at Charlotte
Philip Regalbuto, Trident Technical College
Don Retzlaff, University of North Texas
Jeff Ringenberg, University of Michigan, Ann Arbor
John P. Russo, Wentworth Institute of Technology
Kurt Schmidt, Drexel University
Brent Seales, University of Kentucky
William Shay, University of Wisconsin, Green Bay
Michele A. Starkey, Mount Saint Mary College
William Stockwell, University of Central Oklahoma
Jonathan Tolstedt, North Dakota State University
Boyd Trolinger, Butte College
Muharrem Uyar, City College of New York
Mahendra Velauthapillai, Georgetown University
Kerstin Voigt, California State University, San Bernardino
David P. Voorhees, Le Moyne College
Salih Yurttas, Texas A&M University

A special thank you to all of our class testers:


Pani Chakrapani and the students of the University of Redlands
Jim Mackowiak and the students of Long Beach City College, LAC
Suresh Muknahallipatna and the students of the University of Wyoming
Murlidharan Nair and the students of the Indiana University of South Bend
Harriette Roadman and the students of New River Community College
David Topham and the students of Ohlone College
Dennie Van Tassel and the students of Gavilan College
CONTENTS
PREFACE v CE2 Using Uninitialized Variables 33
SPECIAL FEATURES xxiv PT1 Choose Descriptive Variable Names 33
PT2 Do Not Use Magic Numbers 34
QUICK REFERENCE xxviii
ST1 Numeric Types in C++ 34
ST2 Numeric Ranges and Precisions 35
1 INTRODUCTION 1 ST3 Defining Variables with auto 35

1.1 What Is Programming? 2 2.2 Arithmetic 36


Arithmetic Operators 36
1.2 The Anatomy of a Computer 3
Increment and Decrement 36
C&S Computers Are Everywhere 5
Integer Division and Remainder 36
1.3 Machine Code and Programming Converting Floating-Point Numbers to
Languages 5 Integers 37
C&S Standards Organizations 7 Powers and Roots 38
CE3 Unintended Integer Division 39
1.4 Becoming Familiar with Your
CE4 Unbalanced Parentheses 40
Programming Environment 7
CE5 Forgetting Header Files 40
PT1 Backup Copies 10
CE6 Roundoff Errors 41
1.5 Analyzing Your First Program 11
PT3 Spaces in Expressions 42
CE1 Omitting Semicolons 13
ST4 Casts 42
ST1 Escape Sequences 13
ST5 Combining Assignment and Arithmetic 42
1.6 Errors 14 C&S The Pentium Floating-Point Bug 43
CE2 Misspelling Words 15
2.3 Input and Output 44
1.7 PROBLEM SOLVING Algorithm Design 16 Input 44
The Algorithm Concept 16 Formatted Output 45
An Algorithm for Solving an Investment
Problem 17
2.4 PROBLEM SOLVING First Do It By Hand 47
Pseudocode 18 WE1 Computing Travel Time 48
From Algorithms to Programs 19 HT1 Carrying out Computations 48
HT1 Describing an Algorithm with WE2 Computing the Cost of Stamps 51
Pseudocode 19 2.5 Strings 51
WE1 Writing an Algorithm for Tiling a Floor 21 The string Type 51
Concatenation 52
2 FUNDAMENTAL DATA String Input 52
String Functions 52
TYPES 25
C&S International Alphabets and Unicode 55
2.1 Variables 26
Variable Definitions 26 3 DECISIONS 59
Number Types 28
Variable Names 29 3.1 The if Statement 60
The Assignment Statement 30 CE1 A Semicolon After the if Condition 63
Constants 31 PT1 Brace Layout 63
Comments 31
PT2 Always Use Braces 64
CE1 Using Undefined Variables 33
PT3 Tabs 64

xix
xx Contents

PT4 Avoid Duplication in Branches 65 4.4 The do Loop 111


ST1 The Conditional Operator 65 PT4 Flowcharts for Loops 111
3.2 Comparing Numbers and Strings 66 4.5 Processing Input 112
CE2 Confusing = and == 68 Sentinel Values 112
CE3 Exact Comparison of Floating-Point Reading Until Input Fails 114
Numbers 68 ST1 Clearing the Failure State 115
PT5 Compile with Zero Warnings 69 ST2 The Loop-and-a-Half Problem and the
ST2 Lexicographic Ordering of Strings 69 break Statement 116
HT1 Implementing an if Statement 70 ST3 Redirection of Input and Output 116
WE1 Extracting the Middle 72 4.6 PROBLEM SOLVING Storyboards 117
C&S Dysfunctional Computerized Systems 72
4.7 Common Loop Algorithms 119
3.3 Multiple Alternatives 73
Sum and Average Value 119
ST3 The switch Statement 75 Counting Matches 120
3.4 Nested Branches 76 Finding the First Match 120
CE4 The Dangling else Problem 79 Prompting Until a Match is Found 121
PT6 Hand-Tracing 79 Maximum and Minimum 121
Comparing Adjacent Values 122
3.5 PROBLEM SOLVING Flowcharts 81
HT1 Writing a Loop 123
3.6 PROBLEM SOLVING Test Cases 83 WE1 Credit Card Processing 126
PT7 Make a Schedule and Make Time for
Unexpected Problems 84 4.8 Nested Loops 126
WE2 Manipulating the Pixels in an Image 129
3.7 Boolean Variables and Operators 85
CE5 Combining Multiple Relational Operators 88
4.9 PROBLEM SOLVING Solve a Simpler
CE6 Confusing && and || Conditions 88
Problem First 130
ST4 Short-Circuit Evaluation of Boolean 4.10 Random Numbers and Simulations 134
Operators 89 Generating Random Numbers 134
ST5 De Morgan’s Law 89 Simulating Die Tosses 135
3.8 APPLICATION Input Validation 90 The Monte Carlo Method 136
C&S Artificial Intelligence 92 C&S Digital Piracy 138

4 LOOPS 95 5 FUNCTIONS 141

4.1 The while Loop 96 5.1 Functions as Black Boxes 142


CE1 Infinite Loops 100 5.2 Implementing Functions 143
CE2 Don’t Think “Are We There Yet?” 101 PT1 Function Comments 146
CE3 Off-by-One Errors 101 5.3 Parameter Passing 146
C&S The First Bug 102 PT2 Do Not Modify Parameter Variables 148
4.2 PROBLEM SOLVING Hand-Tracing 103 5.4 Return Values 148
4.3 The for Loop 106 CE1 Missing Return Value 149
PT1 Use for Loops for Their Intended ST1 Function Declarations 150
Purpose Only 109 HT1 Implementing a Function 151
PT2 Choose Loop Bounds That Match WE1 Generating Random Passwords 152
Your Task 110 WE2 Using a Debugger 152
PT3 Count Iterations 110
5.5 Functions Without Return Values 153
Contents xxi

5.6 PROBLEM SOLVING Reusable Functions 154 6.4 PROBLEM SOLVING Adapting
5.7 PROBLEM SOLVING Stepwise Algorithms 198
Refinement 156 HT1 Working with Arrays 200

PT3 Keep Functions Short 161 WE1 Rolling the Dice 203

PT4 Tracing Functions 161 6.5 PROBLEM SOLVING Discovering Algorithms by


PT5 Stubs 162 Manipulating Physical Objects 203
WE3 Calculating a Course Grade 163 6.6 Two-Dimensional Arrays 206
5.8 Variable Scope and Global Variables 163 Defining Two-Dimensional Arrays 207
PT6 Avoid Global Variables 165 Accessing Elements 207
5.9 Reference Parameters 165 Locating Neighboring Elements 208
Computing Row and Column Totals 208
PT7 Prefer Return Values to Reference
Parameters 169 Two-Dimensional Array Parameters 210
CE2 Omitting the Column Size of a Two-
ST2 Constant References 170
Dimensional Array Parameter 212
5.10 Recursive Functions (Optional) 170 WE2 A World Population Table 213
HT2 Thinking Recursively 173
6.7 Vectors 213
C&S The Explosive Growth of Personal
Computers 174 Defining Vectors 214
Growing and Shrinking Vectors 215
Vectors and Functions 216
6 ARRAYS AND VECTORS 179 Vector Algorithms 216
Two-Dimensional Vectors 218
6.1 Arrays 180
PT2 Prefer Vectors over Arrays 219
Defining Arrays 180 ST5 The Range-Based for Loop 219
Accessing Array Elements 182
Partially Filled Arrays 183
CE1 Bounds Errors 184 7 POINTERS AND
PT1 Use Arrays for Sequences of Related STRUCTURES 223
Values 184
C&S Computer Viruses 185 7.1 Defining and Using Pointers 224
Defining Pointers 224
6.2 Common Array Algorithms 185
Accessing Variables Through Pointers 225
Filling 186 Initializing Pointers 227
Copying 186
CE1 Confusing Pointers with the Data to Which
Sum and Average Value 186 They Point 228
Maximum and Minimum 187
PT1 Use a Separate Definition for Each Pointer
Element Separators 187 Variable 229
Counting Matches 187
ST1 Pointers and References 229
Linear Search 188
Removing an Element 188 7.2 Arrays and Pointers 230
Inserting an Element 189 Arrays as Pointers 230
Swapping Elements 190 Pointer Arithmetic 230
Reading Input 191 Array Parameter Variables Are Pointers 232
ST1 Sorting with the C++ Library 192 ST2 Using a Pointer to Step Through
ST2 A Sorting Algorithm 192 an Array 233
ST3 Binary Search 193 CE2 Returning a Pointer to a Local Variable 234
PT2 Program Clearly, Not Cleverly 234
6.3 Arrays and Functions 194
ST3 Constant Pointers 235
ST4 Constant Array Parameters 198
xxii Contents

7.3 C and C++ Strings 235 8.5 Command Line Arguments 274
The char Type 235 C&S Encryption Algorithms 277
C Strings 236 HT1 Processing Text Files 278
Character Arrays 237 WE1 Looking for for Duplicates 281
Converting Between C and C++ Strings 237
8.6 Random Access and Binary Files 281
C++ Strings and the [] Operator 238
Random Access 281
ST4 Working with C Strings 238
Binary Files 282
7.4 Dynamic Memory Allocation 240 Processing Image Files 282
CE3 Dangling Pointers 242 C&S Databases and Privacy 286
CE4 Memory Leaks 243

7.5 Arrays and Vectors of Pointers 243 9 CLASSES 289


7.6 PROBLEM SOLVING Draw a Picture 246
HT1 Working with Pointers 248 9.1 Object-Oriented Programming 290
WE1 Producing a Mass Mailing 249 9.2 Implementing a Simple Class 292
C&S Embedded Systems 250 9.3 Specifying the Public Interface of
7.7 Structures 250 a Class 294
Structured Types 250 CE1 Forgetting a Semicolon 296
Structure Assignment and Comparison 251 9.4 Designing the Data Representation 297
Functions and Structures 252
9.5 Member Functions 299
Arrays of Structures 252
Structures with Array Members 253 Implementing Member Functions 299
Nested Structures 253 Implicit and Explicit Parameters 299
Calling a Member Function from a
7.8 Pointers and Structures 254 Member Function 301
Pointers to Structures 254 PT1 All Data Members Should Be Private; Most
Structures with Pointer Members 255 Member Functions Should Be Public 303
ST5 Smart Pointers 256 PT2 const Correctness 303

9.6 Constructors 304


8 STREAMS 259 CE2 Trying to Call a Constructor 306
ST1 Overloading 306
8.1 Reading and Writing Text Files 260 ST2 Initializer Lists 307
Opening a Stream 260 ST3 Universal and Uniform Initialization
Reading from a File 261 Syntax 308
Writing to a File 262
9.7 PROBLEM SOLVING Tracing Objects 308
A File Processing Example 262
HT1 Implementing a Class 310
8.2 Reading Text Input 265 WE1 Implementing a Bank Account Class 314
Reading Words 265 C&S Electronic Voting Machines 314
Reading Characters 266
9.8 PROBLEM SOLVING Discovering
Reading Lines 267
Classes 315
CE1 Mixing >> and getline Input 268
PT3 Make Parallel Vectors into Vectors of
ST1 Stream Failure Checking 269
Objects 317
8.3 Writing Text Output 270
9.9 Separate Compilation 318
ST2 Unicode, UTF-8, and C++ Strings 272
9.10 Pointers to Objects 322
8.4 Parsing and Formatting Strings 273
Dynamically Allocating Objects 322
The -> Operator 323
The this Pointer 324
Contents xxiii

9.11 PROBLEM SOLVING Patterns for APPENDIX A RESERVED WORD SUMMARY A-1
Object Data 324 APPENDIX B OPERATOR SUMMARY A-3
Keeping a Total 324 APPENDIX C CHARACTER CODES A-5
Counting Events 325
APPENDIX D C++ LIBRARY SUMMARY A-8
Collecting Values 326
Managing Properties of an Object 326 APPENDIX E C++ LANGUAGE CODING
Modeling Objects with Distinct States 327 GUIDELINES A-11
Describing the Position of an Object 328 APPENDIX F NUMBER SYSTEMS AND BIT AND SHIFT
C&S Open Source and Free Software 329 OPERATIONS (E-TEXT ONLY)

10 INHERITANCE 333 GLOSSARY G-1


INDEX I-1
10.1 Inheritance Hierarchies 334
CREDITS C-1
10.2 Implementing Derived Classes 338
CE1 Private Inheritance 341
CE2 Replicating Base-Class Members 341
PT1 Use a Single Class for Variation in Values,
ALPHABETICAL LIST OF SYNTAX BOXES
Inheritance for Variation in Behavior 342 Assignment 30
ST1 Calling the Base-Class Constructor 342 C++ Program 12
10.3 Overriding Member Functions 343 Class Definition 295
Comparisons 67
CE3 Forgetting the Base-Class Name 345
Constructor with Base-Class Initializer 342
10.4 Virtual Functions and Polymorphism 346
Defining an Array 181
The Slicing Problem 346 Defining a Structure 251
Pointers to Base and Derived Classes 347 Defining a Vector 213
Virtual Functions 348 Derived-Class Definition 340
Polymorphism 349 Dynamic Memory Allocation 240
PT2 Don’t Use Type Tags 352 for Statement 106
CE4 Slicing an Object 352 Function Definition 145
CE5 Failing to Override a Virtual Function 353 if Statement 61
ST2 Virtual Self-Calls 354 Input Statement 44
HT1 Developing an Inheritance Hierarchy 354 Member Function Definition 301
WE1 Implementing an Employee Hierarchy for Output Statement 13
Payroll Processing 359
Pointer Syntax 226
C&S Who Controls the Internet? 360
Two-Dimensional Array Definition 207
Variable Definition 27
while Statement 97
Working with File Streams 262
xxiv Special Features

How Tos
C H AP TE R Common and
Errors
Worked Examples
© Steve Simzer/iStockphoto.

© Tom Horyn/iStockphoto.

1 Introduction © Scott Harms/iStockphoto.


Omitting Semicolons 13 Describing an Algorithm
Misspelling Words 15 with Pseudocode 19
Writing an Algorithm for
Tiling a Floor 21

2 Fundamental Using Undefined Variables 33 Computing Travel Time 48


Using Uninitialized Variables 33 Carrying out Computations 48
Data Types
Unintended Integer Division 39 Computing the Cost of Stamps 51
Unbalanced Parentheses 40
Forgetting Header Files 40
Roundoff Errors 41

3 Decisions A Semicolon After the if Implementing an if Statement 70


Condition 63 Extracting the Middle 72
Confusing = and == 68
Exact Comparison of
Floating-Point Numbers 68
The Dangling else Problem 79
Combining Multiple
Relational Operators 88
Confusing && and || Conditions 88

4 Loops Infinite Loops 100 Writing a Loop 123


Don’t Think “Are We There Yet?” 101 Credit Card Processing 126
Off-by-One Errors 101 Manipulating the Pixels
in an Image 129

5 Functions Missing Return Value 149 Implementing a Function 151


Generating Random Passwords 152
Using a Debugger 152
Calculating a Course Grade 163
Thinking Recursively 173
Special Features xxv

Programming Computing &


Special Topics
Tips Society
© MacDaddy/Dreamstime.com. © Nathan Winter/iStockphoto. © Mishella/Dreamstime.com.
Backup Copies 10 Escape Sequences 13 Computers Are Everywhere 5
Standards Organizations 7

Choose Descriptive Numeric Types in C++ 34 The Pentium Floating-Point Bug 43


Variable Names 33 Numeric Ranges and Precisions 35 International Alphabets
Do Not Use Magic Numbers 34 Defining Variables with auto 35 and Unicode 55
Spaces in Expressions 42 Casts 42
Combining Assignment and
Arithmetic 42

Brace Layout 63 The Conditional Operator 65 Dysfunctional Computerized


Always Use Braces 64 Lexicographic Ordering Systems 72
Tabs 64 of Strings 69 Artificial Intelligence 92
Avoid Duplication in Branches 65 The switch Statement 75
Compile with Zero Warnings 69 Short-Circuit Evaluation of
Boolean Operators 89
Hand-Tracing 79
De Morgan’s Law 89
Make a Schedule and Make Time
for Unexpected Problems 84

Use for Loops for Their Clearing the Failure State 115 The First Bug 102
Intended Purpose Only 109 The Loop-and-a-Half Problem Digital Piracy 138
Choose Loop Bounds That and the break Statement 116
Match Your Task 110 Redirection of Input and Output 116
Count Iterations 110
Flowcharts for Loops 111

Function Comments 146 Function Declarations 150 The Explosive Growth of


Do Not Modify Parameter Constant References 170 Personal Computers 174
Variables 148
Keep Functions Short 161
Tracing Functions 161
Stubs 162
Avoid Global Variables 165
Prefer Return Values to
Reference Parameters 169
xxvi Special Features

How Tos
C H AP TE R Common and
Errors
Worked Examples
© Steve Simzer/iStockphoto.

© Tom Horyn/iStockphoto.

6 Arrays and Vectors © Scott Harms/iStockphoto.


Bounds Errors 184 Working with Arrays 200
Omitting the Column Size of Rolling the Dice 203
a Two-Dimensional A World Population Table 213
Array Parameter 212

7 Pointers and Structures Confusing Pointers with the Working with Pointers 248
Data to Which They Point 228 Producing a Mass Mailing 249
Returning a Pointer to a
Local Variable 234
Dangling Pointers 242
Memory Leaks 243

8 Streams Mixing >> and getline Input 268 Processing Text Files 278
Looking for for Duplicates 281

9 Classes Forgetting a Semicolon 296 Implementing a Class 310


Trying to Call a Constructor 306 Implementing a Bank
Account Class 314

10 Inheritance Private Inheritance 341 Developing an Inheritance


Replicating Base-Class Hierarchy 354
Members 341 Implementing an Employee
Forgetting the Base-Class Name 345 Hierarchy for Payroll
Processing 359
Slicing an Object 352
Failing to Override a
Virtual Function 353
Special Features xxvii

Programming Computing &


Special Topics
Tips Society
© MacDaddy/Dreamstime.com. © Nathan Winter/iStockphoto. © Mishella/Dreamstime.com.
Use Arrays for Sequences Sorting with the C++ Library 192 Computer Viruses 185
of Related Values 184 A Sorting Algorithm 192
Prefer Vectors over Arrays 219 Binary Search 193
Constant Array Parameters 198
The Range-Based for Loop 219

Use a Separate Definition Pointers and References 229 Embedded Systems 250
for Each Pointer Variable 229 Using a Pointer to Step
Program Clearly, Not Cleverly 234 Through an Array 233
Constant Pointers 235
Working with C Strings 238
Smart Pointers 256

Stream Failure Checking 269 Encryption Algorithms 277


Unicode, UTF-8, and Databases and Privacy 286
C++ Strings 272

All Data Members Should Be Private; Overloading 306 Electronic Voting Machines 314
Most Member Functions Initializer Lists 307 Open Source and
Should Be Public 303 Universal and Uniform Free Software 329
const Correctness 303 Initialization Syntax 308
Make Parallel Vectors into
Vectors of Objects 317

Use a Single Class for Variation in Calling the Base-Class Who Controls the Internet? 360
Values, Inheritance for Variation Constructor 342
in Behavior 342 Virtual Self-Calls 354
Variable and Constant Definitions Conditional Statement
Type Name Initial value Condition

int cans_per_pack = 6; if (floor >= 13)


{ Executed when
actual_floor = floor - 1; condition is true
const double CAN_VOLUME = 0.335;
}
else if (floor >= 0) Second condition (optional)
{
Mathematical Operations actual_floor = floor;
}
#include <cmath> else
pow(x, y) Raising to a power x y { Executed when all
sqrt(x) Square root x cout << "Floor negative" << endl; conditions are false
} (optional)
log10(x) Decimal log log10(x)
abs(x) Absolute value |x|
String Operations
sin(x)
cos(x) Sine, cosine, tangent of x (x in radians) #include <string>
string s = "Hello";
tan(x) int n = s.length(); // 5
string t = s.substr(1, 3); // "ell"
string c = s.substr(2, 1); // "l"
Selected Operators and Their Precedence char ch = s[2]; // 'l'
(See Appendix B for the complete list.) for (int i = 0; i < s.length(); i++)
{
[] Array element access string c = s.substr(i, 1);
++ -- ! Increment, decrement, Boolean not or char ch = s[i];
* / % Multiplication, division, remainder Process c or ch
}
+ - Addition, subtraction
< <= > >= Comparisons
== != Equal, not equal Function Definitions
&& Boolean and Return type Parameter type and name
|| Boolean or
double cube_volume(double side_length)
= Assignment {
double vol = side_length * side_length * side_length;
return vol;
Loop Statements } Exits function and returns result.
Reference parameter
Condition
void deposit(double& balance, double amount)
while (balance < TARGET) {
{ balance = balance + amount;
year++; Executed }
while condition Modifies supplied argument
balance = balance * (1 + rate / 100);
} is true Arrays
Initialization Condition Update Element type Length
for (int i = 0; i < 10; i++) int numbers[5];
{ int squares[] = { 0, 1, 4, 9, 16 };
cout << i << endl; int magic_square[4][4] =
} {
{ 16, 3, 2, 13 },
{ 5, 10, 11, 8 },
Loop body executed { 9, 6, 7, 12 },
do at least once { 4, 15, 14, 1 }
{ };
cout << "Enter a positive integer: ";
cin >> input; for (int i = 0; i < size; i++)
} {
while (input <= 0); Process numbers[i]
}
Vectors Range-based for Loop
#include <vector> An array, vector, or other container (C++ 11)
Element type Initial values (C++ 11)
for (int v : values)
vector<int> values = { 0, 1, 4, 9, 16 }; {
cout << v << endl;
Initially empty }
vector<string> names;
Add elements to the end
names.push_back("Ann");
names.push_back("Cindy"); // names.size() is now 2
Output Manipulators
names.pop_back(); // Removes last element #include <iomanip>

names[0] = "Beth"; // Use [] for element access endl Output new line
fixed Fixed format for floating-point
setprecision(n) Number of digits after decimal point
Pointers for fixed format
int n = 10; setw(n) Field width for the next item
int* p = &n; // p set to address of n left Left alignment (use for strings)
*p = 11; // n is now 11 right Right alignment (default)
20300 setfill(ch) Fill character (default: space)
n = 11 Memory address

p = 20300
Class Definition
int a[5] = { 0, 1, 4, 9, 16 }; class BankAccount
p = a; // p points to start of a {
*p = 11; // a[0] is now 11 public:
Constructor declaration
p++; // p points to a[1] BankAccount(double amount);
void deposit(double amount); Member function declaration
p[2] = 11; // a[3] is now 11
double get_balance() const;
Accessor member function
...
a = 11 20400 private: Data member
1 double balance;
4 };
11
void BankAccount::deposit(double amount) Member function
16
{ definition
balance = balance + amount;
p = 20404 }

Input and Output Inheritance


#include <iostream> Derived class Base class
cin >> x; // x can be int, double, string
cout << x; class CheckingAccount : public BankAccount
{
while (cin >> x) { Process x } public: Member function
if (cin.fail()) // Previous input failed void deposit(double amount); overrides base class
private:
Added data member
int transactions;
}; in derived class
#include <fstream>
string filename = ...;
ifstream in(filename); void CheckingAccount::deposit(double amount)
ofstream out("output.txt"); { Calls base class
BankAccount::deposit(amount); member function
string line; getline(in, line); transactions++;
char ch; in.get(ch); }
Another random document with
no related content on Scribd:
figures. At a cost of £5,000 Le Blon had produced 4,000 copies of
his prints—these were from twenty-five plates—which, if all had been
sold at the prices fixed, would have produced a net loss of £2,000.
Even Colonel Guise could hardly consider these as satisfactory
business methods, and the company had already been reorganised,
with a new manager named Guine, who had introduced a cheaper
and more profitable way of producing the prints. It was all to no
purpose. Prints to the value of only £600 were sold at an expenditure
of £9,000, while the tapestry-weaving branch of the business—also
Le Blon’s scheme—showed an even more disproportionate result.
Bankruptcy followed as a matter of course, and Le Blon narrowly
escaped imprisonment.
The colour-printing of engravings, though artistically promising, while
still experimental, had certainly proved a financial failure, but Le
Blon, nothing daunted, sought to explain and justify his principles
and his practice in a little book, called “Coloritto, or the Harmony of
Colouring in Painting, reduced to mechanical practice, under easy
precepts, and infallible rules.” This he dedicated to Sir Robert
Walpole, hoping, perhaps, that the First Lord of the Treasury, who
had just restored the nation’s credit, might do something for an
inventive artist’s. Next he was privileged to submit his inventions to
the august notice of the Royal Society. Le Blon had always his
opportunities, an well a his rebuff from fortune, but his faith in himself
and his ideas was unswerving; moreover, he had the gift of
transmitting this faith to others. At last a scheme for imitating
Raphael’s cartoons in tapestry, carried on at works in Chelsea, led to
further financial disaster and discredit, and Le Blon was obliged to fly
from England.
In Paris he resumed his colour-printing, inspiring and influencing
many disciples and imitators, among them Jacques Fabian Gautier
D’Agoty, who afterwards claimed to have invented Le Blon’s process,
and transmitted it to his sons. In Paris, in 1741, Le Blon died, very,
very poor, but still working upon his copper-plates. It was doubtless
during Le Blon’s last years in Paris that Horace Walpole met him.
“He was a Fleming (sic), and very far from young when I knew him,
but of surprising vivacity and volubility, and with a head admirably
mechanic; but an universal projector, and with, at least, one of the
qualities that attend that vocation, either a dupe or a cheat: I think
the former, though, as most of his projects ended in the air, the
sufferers believed the latter. As he was much an enthusiast, perhaps
like most enthusiasts he was both one and t’other.” As a matter of
fact, Le Blon was neither a dupe nor a cheat; he was simply a
pioneer with all the courage of his imagination and invention; and no
less an authority than Herr Hans W. Singer, of Vienna, has
considered him, with all his failures and shortcomings, of sufficient
artistic importance to be worthy of a monograph.
If, by a more judicious selection of pictures for copying, Le Blon had
been able to create a popular demand, and to ensure general
encouragement for his venture, how different might have been the
story of colour-printing, how much fuller its annals. For Le Blon’s
ultimate failure was not owing to the comparative impossibility or
getting infallibly the required harmonics of his tones with only the
three cardinal colours, and the necessity to add a fourth plate with a
qualifying black, or to the difficulty in achieving the exactness of
register essential to the perfect fusing of the tones of several plates.
Those were serious obstacles, certainly, hindering complete artistic
success; but, judging from the surprising excellence of the best of Le
Blon’s actual achievements, they would doubtless have been
surmounted for all practical purposes. The real cause of the failure
was, I suggest, that the pictures actually reproduced made no appeal
to the people of England, consequently there was no public demand
for the prints. It was a close time for the fine arts in this country. The
day of the public picture-exhibition was nearing, but it had not yet
arrived. The aristocratic collector and the fashionable connoisseur
represented the taste of the country, for popular taste there was
none. Romance and sentiment were quite out of fashion, and the
literature of the day was entirely opposed to them. Nor were there
any living painters with even one touch of nature. The reign of
George I. was indeed a depressing time for the graphic arts. Society,
heavily bewigged and monstrously behooped, was too much
concerned with its pastimes and intrigues, its affectations, caprices
and extravagances, to cultivate any taste or care for beauty. Kent,
the absurdly fashionable architect, was ruling in place of the
immortal Wren, and Kneller was so long and so assuredly the
pictorial idol of the country that Pope, its poet-in-chief, could actually
write of him that “great Nature fear’d he might outvie her works.”
Then, all else of pictorial art meant either Thornhill’s wearisome
ceilings and stair-cases, or the stiff and tasteless portraiture, with
stereotyped posture, of the lesser Knellers, such as Jonathan
Richardson, Highmore, and Jervas, whom Pope made even more
ridiculous by his praises.
With only such painters as these to interpret, what chance had even
such admirable engravers as John Smith, George White, John
Simon, Faber, Peter Pelham, whose mezzotints even were
beginning to wane in favour for lack of pictorial interest? It is no great
wonder then that, seeing Le Blon’s failure, in spite of all his influence
and achievement, the engravers in mezzotint were not eager to try
the principles of his “Coloritto” in their own practice, and so colour-
printing suffered a set-back in this country. But Le Blon’s prints are of
great value to-day. What, then, has become of those 9,000 copies
printed by the Picture Office? The £600 worth sold before the
bankruptcy must have represented about a thousand, yet these
impressions from Le Blon’s fifty-plates are of extreme rarity even in
the museums of the world, and it has been suggested by Herr
Singer, and also by Mr. A. M. Hind, in his valuable “History of
Engraving and Etching,” that many copies of the large prints,
varnished over, may be hanging in old houses under the guise of oil
paintings, thus fulfilling their original purpose. It is an interesting
conjecture, and how plausible one may judge from the varnished
copies in the British Museum.
Le Blon’s really important venture inspired no imitators in England,
but it was followed by a few experimental attempts to embellish
engravings with colour. These were chiefly adaptations of the old
chiaroscuro method, surface-colour being obtained by using several
wood-blocks in combination with engraved copper-plates. Arthur
Pond and Charles Knapton, painters both, imitated a number of
drawings in this manner, the designs being etched; while, some
years earlier, Elisha Kirkall (“bounteous Kirkall” of the “Dunciad”) had
successfully used the coloured wood-blocks with mezzotint plates,
strengthened with etched and graven lines. His pupil, J. B. Jackson,
however, engraved only wood for his remarkable prints. But these
experiments were merely sporadic; they led to nothing important and
continuous in the way of colour-printing.
Meanwhile, the prints of Hogarth, with their marvellous pictorial
invention, mordant satire, and moral illumination, took the fancy of
the town without the lure of colour, and cultivated in the popular mind
a new sense of picture, concerned with the live human interest of the
passing hour. Other line-engravers, too,—Vivares, Woollett,
Ravenet, Major, Strange,—with more masterly handling of the
graver, were, through the new appeal of landscape, or the beauties
of Rembrandt and the Italian masters, or the homely humours of
Dutch genre, winning back the popular favour for their art.
Though the call for the colour-print had not yet arrived, the way was
preparing for it. With this widening public interest in pictorial art, a
dainty sense of tone was awakened by the porcelain now
efflorescing all aver the country. Then, when Reynolds was bringing
all the graces to his easel, the urbane influence for beauty spread
from the master’s painting-room at 47, Leicester Fields—as the
Square was then called—to all the print-shops in town. And the year
—1764—that saw the death of Hogarth was the year in which
Francesco Bartolozzi came to England, bringing with him into the
engraving-world fresh influences of grace and delicacy which
gradually ripened for colour.
II.
The sentimental mood for the storied picture was now being fostered
by the universal reading of the novel, which in its mid-eighteenth-
century form gave its readers new experiences in the presentation of
actual contemporary life, with analysis of their feelings and
cultivation of there sensibilities. Pamela and Clarissa Harlowe,
Sophia Western and Amelia, Olivia, Maria, were as living in interest
as any of the beautiful high-born ladies whose portraits in mezzotint,
translated from the canvasses of the great painters, appealed from
the printsellers’ windows in all the monochrome beauty of their
medium. The public, steeped now in sentiment, wanted to see their
imaginary heroines in picture: nor had they long to wait. The Royal
Academy had become a vital factor in forming public taste, and the
printsellers’ shops were its mirrors. But not all its members and
exhibitors were Gainsboroughs and Reynoldses. There were, for
instance, Angelica Kauffman and Cipriani, with their seductive Italian
graces of design; there was Bartolozzi, with his beautiful
draughtsmanship, and his brilliant facile craft on the copper-plate,
but the medium that should bring these into familiar touch with
popular taste was still to seek. However, it was at hand, and the man
who found this medium, and brought it to the service of popular art,
was William Wynne Ryland, “engraver to the King.”
Whether the so-called crayon method of engraving, in imitation of
soft chalk drawings, was invented by Jean Charles François, or
Gilles Demarteau, or Louis Bonnet—all three claimed the credit of it
—it was, at all events, from François, whose claim had obtained
official recognition, that Ryland, the pupil of Ravenet and Le Bas,
and, in a measure, of Boucher, learned the method while he was still
a student in Paris. Only later in his career, however, long after he
had left behind him his student days in Paris and Rome, and
achieved prosperity in London as a line-engraver and printseller, with
royal patronage, and with social success as a man of fashion and
pleasure, did he remember the process that François had imparted
to him. Then, in his necessity, when his extravagances had brought
him to bankruptcy, he called the dotted crayon manner to memory,
and saw in stipple-engraving, if suitably employed, a possible asset
of importance. Compared with line and even with mezzotint it was a
very easy and rapid way of engraving, and though, of course, it could
not compare with either in nobility, richness and brilliance of effect,
Ryland realised that its soft rendering of tones by artistically
balanced masses of dots might be adapted to dainty and delicate
drawings. The most fortunate opportunity for proving this was at
hand. He had some personal acquaintance with Angelica Kauffman,
whom Lady Wentworth had brought to London some ten years
before, and whose beauty, talents and personal charm had
meanwhile made her a fashionable artistic idol, with Society and its
beauties flocking to her studio to be painted or to buy her pictures.
Having first tested his stippling with his own designs, gracefully
French in manner, which he published soon afterwards as “Domestic
Employments,” Ryland suggested the idea of stipple-engraving to
the sympathetic young painter. When he had experimented with one
or two of her drawings, she gladly recognised that stipple was the
very medium for the interpretation of her work to the public. The first
prints sold “like wildfire,” and so satisfied was Ryland of the profitable
prospect, that, on the strength of it, he promptly re-established
himself in a printselling business at 159, Strand. His confidence was
amply justified, the public being quick to show their appreciation of
the new method, introduced as it was with all the persuasion of the
fair Angelica’s graceful, fanciful designs of classic story and allegory.
This was in 1775, and within a very short time Ryland found that,
rapidly as she designed and he engraved, he could scarcely keep
pace with the demand for these prints, which, the more readily to
crave the popular fancy, he printed in red ink, to imitate red chalk,
later to be known as the “Bartolozzi red.”
Ryland had called Bartolozzi into consultation, and the gifted Italian
engraver, with his greater mastery of technique, his delicate sense of
beauty, and his finer artistic perceptions, had seen all that might be
done with the new way of stipple; he saw also its limitations. With
enthusiasm Bartolozzi and Ryland had worked together till they had
evolved from the crayon manner of François a process of engraving
which proved so happily suited to the classes of fanciful and
sentimental prints now fast becoming the vogue, that it simply
jumped into a popularity which no other medium of the engraver’s art
had ever attained.
The stipple method may be thus described. The copper-plate was
covered with an etching-ground, on to which the outlined picture was
transferred from paper. Then the contours of the design were lightly
etched in a series of dots, all the dark and middle shadows being
rendered by larger or more closely etched dots, the later engravers
using even minute groups of dots. This accomplished, the acid was
next applied with very great care, and all the etched dots bitten in.
The waxen ground was then removed from the plate, and the work
with the dry-point and the curved stipple-graver was commenced.
With these tools the lighter shadows were accomplished, and the
bitten portions of the picture were deepened and strengthened
wherever required, to attain greater fulness or brilliance of effect.
Engraving in dots was, of course, no new thing; as an accessory to
line-engraving it had often been called into service by the earlier
artists. Giulio Campagnola, Albert Dürer, Agostino Veneziano,
Ottavio Leoni, for example, had used it; we frequently find it
employed by our own seventeenth-century line-men the better to
suggest flesh-tones, and Ludwig von Siegen, in describing his
invention of mezzotint in 1642, includes the “dotted manner” among
the known forms of engraving. Then there was the opus mallei, or
method of punching dots in the plate with a mallet and awl, which
was successfully practised by Jan Lutma, of Amsterdam, late in the
seventeenth century. This may be considered the true precursor of
stipple, just as the harpsichord, with the same keyboard, but a
different manner of producing the notes, was the precursor of the
pianoforte; but it must have been a very laborious process, and
Lutma found few imitators.
Under the ægis of Ryland and Bartolozzi, however, and with the
inspiration of Angelica Kauffman’s “harmonious but shackled fancy,”
as a contemporary critic put it, for its initial impetus, stipple was
developed as a separate and distinctive branch of the engraver’s art.
Its popularity was now to be further enhanced by the gentle and
persuasive aid of colour. Ryland had seen many specimens of
colour-printing in Paris, when he was with François and with
Boucher; he now bethought him that, just as the public fancy had
been captured by red-chalk imitations, so might it be enchanted by
engraved representations of water-colour drawings actually printed
in colours. Angelica Kauffman and Bartolozzi eagerly encouraged
the idea, and the two engravers, after many experiments,
determined the best process of colouring and printing from the
plates. Apparently they rejected the multi-plate method tried six
years previously by that interesting artist Captain William Baillie; and
Ryland’s earliest colour-prints were partially tinted only with red and
blue. Mrs. Frankau tells us, on the authority of a tradition handed
down in his old age from James Minasi, one of Bartolozzi’s most
trusted pupils, that an Alsatian named Seigneuer was responsible for
all the earlier colour-printed impressions of Ryland’s and Bartolozzi’s
stipples after Angelica Kauffman and Cipriani, that then he set up on
his own account as a colour-printer, much recommended by
Bartolozzi, and largely employed by the publishers, and that his
printing may be traced, though unsigned, by a transparency of tone
due to the use of a certain vitreous white which he imported in a dry
state from Paris. Minasi must, of course, have been a perfect mine of
Bartolozzi traditions, but when my father in his boyhood knew him
and his musical son, the distinguished engraver would talk of nothing
but music, for in 1829, with steel plates superseding the copper, and
lithography triumphant, there seemed no prospect that the coloured
stipples, already some time out of fashion, would eighty years later
be inspiring curiosity as to how they were done. One sees, of course,
many feeble colour-prints of the period, which of old the
undiscriminating public accepted as readily as to-day they buy, for
“old prints,” modern cheap foreign reproductions which would
disgrace a sixpenny “summer number.” On the other hand, the really
fine examples of the old-time colour-printing, combined with brilliant
engraving—and, of course, only fine things are the true collector’s
desiderata, irrespective of margins and “state” letterings, and other
foolish fads—are certainly works of art, though a very delicate art of
limited compass.
These colour-prints were done with a single printing, and the plate
had to be freshly inked for each impression. The printer would have
a water-colour drawing to work from, and having decided upon the
dominant tint, with this he would ink over the whole engraved surface
of the plate. Then he would wipe it almost entirely out of the incisions
and punctures on the copper which had retained it, leaving just a
sufficient harmonising ground-tint for the various coloured inks,
carefully selected as to tints, which were next applied in the exact
order and degree to ensure the right harmonies. All this required the
nicest care directed by a very subtle sense of colour. Most difficult of
all, and reserved for the last stage of the inking, was adding the
flesh-tints, an operation of extreme delicacy. Then, before putting the
plate in the printing-press, it had to be warmed to the exact degree of
sensitiveness which should help the colours to fuse with tenderness
and softness, without losing any brilliant quality of tone. This was not
the least anxious part of the work, needing highly-trained artistic
sensibility on the part of the printer. How artistically important this
matter of warming the plates must have been in printing a
combination of coloured inks may be judged when I say that I have
been privileged to watch Whistler warming his etched plates ready
for the printing-press, and seen him actually quivering with excited
sensibility as the plate seemed to respond sensitively to the
exigence of his own exquisite sense of tone. But, of course, no
eighteenth-century colour-prints, however charming in tone, suggest
that there were any Whistlers engaged in the printing of them.
Perhaps that is why our modern master of the copper-plate never
cared for these dainty things, as he did greatly care for Japanese
colour-prints. The old printers, however, had their own definite
manner of work, and their own tricks of experience for producing
pleasing and brilliant effects. By the dusting of a little dry colour on to
the moist, here and there, during the printing process, they could
heighten tones, or by very, very lightly dragging a piece of muslin
over the surface of the plate they could persuade the tints to a more
tender and harmonious intimacy. Of course, when the plate was
printed, the colour was taken only by the dots and lines of the
engraving, the white paper peeping between. If would-be buyers of
colour-prints would only remember this simple fact, and examine the
stippling closely to see whether it really shows the colour, they would
not so constantly be deceived into buying entirely hand-coloured
prints. Whether the old printers and engravers authorised and
sponsored the touching-up of the prints with water-colour which one
almost invariably finds, at least to some slight extent, even in the
best examples, with rare exceptions, it is impossible to determine. At
all events, it is presumable that the eyes and lips were touched up
before the prints left the publishers’ shops.
It must not be supposed, however, that colour had ousted from
public favour the print in monochrome. As a matter of fact, it was
usually only after the proofs and earlier brilliant impressions in
monochrome had been worked off, and the plate was beginning to
look a little worn, that the aid of colour was called in to give the print
a fresh lease of popularity. Indeed, with mezzotint a slightly worn
plate generally took the colours most effectively. This is why one
sees so very seldom an engraver’s proof in colours, the extreme
rarity of its appearance making always a red-letter moment at
Christie’s. Therefore, in spite of the ever-widening vogue of the
colour-print, it was always the artist and engraver that counted, while
the printer in colours was scarcely ever named. And the new industry
of stipple-engraving may be said to have been, in its first days of
popularity, monopolised almost by Ryland and Bartolozzi, in
association with Angelica Kauffman and John Baptist Cipriani.
Cipriani had, by his elegant and tasteful designs, won immediate
favour on his arrival in England, and even the Lord Mayor’s coach
was decorated with panels of his painting. His style prepared the
way for Angelica Kauffman, and together they soon brought a new
pictorial element to the service of home-decoration. Their graceful
rhythmic treatment of classic fables was just what the brothers Adam
wanted for their decorative schemes, and the two Italian artists were
extensively employed to paint panels for walls and ceilings. In time
the fair Angelica outdistanced Cipriani in popularity, and, painting
panels for cabinets, commodes, pier-table tops, and other pieces of
decorative furniture, her taste was soon dominating that of the
fashionable world. No wonder then that, when Ryland and
Bartolozzi, through the medium of their facile and adaptable
engravings, made her charming, if not flawlessly drawn,
compositions readily accessible, the public eagerly bought them,
and, framing them, generally without any margin, according to their
own oval and circular forms, found them the very mural adornments
that the prevailing Adam taste seemed to suggest. In monochrome
or in colours, the prints, with their refined and fluent fancies, pictured
from Horace, Ovid, Virgil, Homer, and Angelica’s beautiful face and
figure vivid in several, had an extraordinarily wide appeal. They
flattered the fashionable culture of the day, when to quote Horace
familiarly in ordinary conversation was almost a patent of gentility.
On the continent they were even copied for the decoration of
porcelain.
For Ryland this meant another spell of prosperity: it also meant
disaster. His constant thirst for pleasure, and his ambition to shine as
a fine gentleman, stimulated by such easy and seemingly
inexhaustible means of money-making, led him into fatal
extravagances. Accused of forging a bill, instead of facing the
charge, of which he protested his innocence, he stupidly hid himself
and tried ineffectually to cut his own throat. After that, some flimsy
evidence procured his condemnation, and, as William Blake, looking
in Ryland’s face, had predicted years before, he was hanged at
Tyburn in 1783.
They could have done no worse to a highwayman; and, after all, by
the introduction of stipple-engraving Ryland had certainly increased
the people’s stock of harmless pleasure. In his own stippling there
was a delicacy of touch, a smoothness of effect, equal to
Bartolozzi’s, but with less tenderness and suppleness of tone.
Evidently he formed his style to suit the designs of Angelica
Kauffman, which it rendered with appreciation of their refinement.
This will be seen in the charming Cupid bound to a Tree by Nymphs,
among our illustrations, and many other pleasing plates, such as
Venus presenting Helen to Paris, Beauty crowned by Love, The
Judgment of Paris, Ludit Amabiliter, O Venus Regina, Olim Truncus,
Dormio Innocuus, Juno Cestum, Maria, from Sterne’s “Sentimental
Journey,” for which Miss Benwell, the painter, is said to have sat;
Patience and Perseverance; Morning Amusement, a fanciful portrait
of Lady Mary Wortley Montagu, embroidering at a tambour-frame,
and wearing the Turkish costume which she so graphically describes
in one of her letters, and in which Kneller had painted her at the
instigation of Pope; fancy portraits, too, of the adventurous Lady
Hester Stanhope, and Mary, Duchess of Richmond.
Although Angelica Kauffman had Bartolozzi and his numerous
disciple—which meant, of course, most of the best stipple-engravers
of the day—at the service of her prolific pencil, her favourite of all
was Thomas Burke. In this she proved her sound judgment, for
certainly no other stipple-engraver, not Bartolozzi himself, could
equal Burke’s poetic feeling upon the copper, or surpass him in his
artistic mastery of the medium. After studying, it is believed, at the
art school of the Royal Dublin Society, he came to London to learn
mezzotint-engraving under his talented countryman, John Dixon,
who was winning reputation as one of Reynolds’s ablest
“immortalisers,” to borrow the master’s own word. Burke soon
showed that he could scrape a mezzotint with the best of them, but
the pupil’s manner developed on his own lines, differing from the
master’s in a more tender and luminous touch, a greater suavity of
tone. These qualities are patent in his beautiful rendering of Angelica
Kauffman’s Telemachus at the Court of Sparta, and it was only
natural that they should suggest his adopting the stipple method.
The technique he learnt from Ryland, and unquestionably he
“bettered the instruction.” The painter’s sense of effect, which Dixon
had taught him to translate into mezzotint, was of incalculable value
to him in his use of the new medium, for, by an individual manner of
infinitely close stippling suggestive of the rich broad tone-surfaces of
mezzotint, he achieved, perhaps, the most brilliant and beautiful
effects that stipple-engraving has ever produced. Burke, in fact, was
an artist, who, seeing a picture, realised how to interpret it on the
copper-plate with the just expression of all its tone-beauties. There is
a glow about his engraving which shows the art of stipple at the very
summit of its possibilities, and, happily, brilliant impressions of
several of his plates were printed in colours. Thus, in such beautiful
prints as Lady Rushout and Daughter, Rinaldo and Armida, A Flower
painted by Varelst, Angelica Kauffman as Design listening to the
Inspiration of Poetry, Cupid and Ganymede, Jupiter and Calisto,
Cupid binding Aglaia, Una and Abra, to name, perhaps, the gems
among Burke’s Kauffman prints, is shown what artistic results could
be compassed when stipple-engraving and colour-printing met at
their best. If, however, Angelica’s engaging fantasies inspired Burke
to his masterpieces, not less exquisite was his rendering of Plimer’s
miniatures of the Rushout daughters, while his art could interpret
with equal charm the homely idyllic picture, as may be seen in the
pretty Favourite Chickens—Saturday Morning—Going to Market,
after the popular W. R. Bigg, and The Vicar of the Parish receiving
his Tithes, after Singleton. But there are pictures by the masters one
would like Burke to have engraved. The strange thing is that he did
not do them.
Most of the engravers were now wooing the facile and profitable
popularity of the stipple method and the colour-print and all the
favourite painters of the day, from the President of the Royal
Academy to the lady amateur, were taking advantage of the fashion.
The constancy and infinitude of the demand were so alluring, and
the popular taste, never artistically very exacting, had been flattered
and coaxed into a mood which seemed very easy to please. It asked
only for the pretty thing.
Sir Joshua Reynolds, seeing, doubtless, what delicious and popular
things Bartolozzi had made of Cipriani’s Cupids and Graces, was
readily induced to lend himself, in the lighter phases of his art, to the
copper-plates of the stipple-engravers, pleasantly assisted by the
colour-printer. Still leaving the more dignified and pictorially elaborate
examples of his brush, the beautiful, elegant, full-length portraits of
lovely and distinguished women and notable men, to the gracious
interpretation of mezzotint, which had served him so nobly and
faithfully, he found that, in the hands of such artists on copper as
Bartolozzi, John Jones, Caroline Watson, Wilkin, Cheesman,
Dickinson, Nutter, Schiavonetti, Marcuard, Thomas Watson, John
Peter Simon, Grozer, Collyer, J. R. Smith, the delicate art of stipple
could express all the sweetness, tenderness, and grace he intended
in the pictures he enjoyed to paint of children and of girlish beauty.
So we have such delightful prints, both in monochrome and in colour,
as the Hon. Anne Bingham and Lavinia, Countess Spencer, Lady
Betty Foster, The Countess of Harrington and Children, Lady Smyth
and her Children, Lord Burghersh, Hon. Leicester Stanhope,
Simplicity (Miss Gwatkin), The Peniston Lamb Children, all of
Bartolozzi’s best; Lady Cockburn and her Children, and Master
Henry Hoare, the Hon. Mrs. Stanhope as “Contemplation,” Lady
Beauchamp (afterwards Countess of Hertford), A Bacchante (Mrs.
Hartley, the actress, and her child), the Spencer children in The
Mask, and The Fortune Tellers, Miss Elizabeth Beauclerc (Lady
Diana’s daughter and Topham Beauclerc’s) as “Una,” Muscipula,
Robinetta, Felina, Collina, The Sleeping Girl, Infancy, Lady
Catherine Manners, The Reverie, Lord Grantham and his Brothers,
Mrs. Sheridan as “St. Cecilia,” Maternal Affection (Lady Melbourne
and child), Perdita (Mrs. Robinson), Mrs. Abington as “Roxalana,”
The Age of Innocence, The Infant Academy, The Snake in the Grass
—but the list is endless. All collectors of colour-prints know how
desirable these Reynolds’ stipples are to charm their walls withal, but
almost unique must be the collector who can also hang among them
Keating’s joyous mezzotint of Reynolds’s famous portrait of the
Duchess of Devonshire and her baby daughter, printed in colours.
This is one of those rare examples which, with J. R. Smith’s
Bacchante and Nature (Lady Hamilton), Henry Meyer’s Nature too,
some of the Morland prints by the Wards, Smith, and Keating; S. W.
Reynolds’s Countess of Oxford, J. R. Smith’s Mrs. Bouverie, and a
few other important Hoppner prints, C. Turner’s Penn Family, after
Reynolds, Smith’s Synnot Children, after Wright of Derby, and Mrs.
Robinson, after Romney, prove that, in the hands of an engraver with
a painter’s eye, mezzotint could respond to the coloured inks as
harmoniously and charmingly as stipple.
Gainsborough—at least, the Gainsborough of unapproachable
mastery and inimitable beauty, the greatest glory of our eighteenth
century art—seems to have been beyond the colour-printer’s
ambition. With the exception of the Hobbinol and Ganderetta
(Tomkins), reproduced here, and the Lavinia (Bartolozzi), both of
which were painted for Macklin’s “British Poets,” I doubt if anything
important of Gainsborough’s was reproduced in coloured stipple,
and, of course, these things cannot be said adequately to represent
the master; while, as to mezzotint, W. Whiston Barney’s version of
Gainsborough’s Duchess of Devonshire was, I understand, printed in
colours, though impressions are extremely rare. Romney’s exquisite
art, on the other hand, with its gracious simplicity of beauty, lent itself
more readily to the colour-printed copper-plate. Among the
numberless tinted engravings with which the small-paned windows
of the eighteenth-century print-shops were crowded, none ingratiated
themselves more with the connoisseurs than the Romneys. So, in
any representative collections of colour-prints to-day, among the
finest and most greatly prized examples must be the lovely Emma
and Serena (Miss Sneyd) of John Jones, Mrs. Jordan as “The
Romp” of Ogborne, Miss Lucy Vernon as “The Seamstress,” and
Lady Hamilton as “The Spinster” of Cheesman, the beautiful Emma
also as a “Bacchante” by Knight, as “Sensibility” by Earlom, and as
“Nature” in the two mezzotint versions, just mentioned, by J. R.
Smith and Henry Meyer.
Of course the pictorial miniatures of the fashionable Richard
Cosway, with their light, bright scheme of draughtsmanship, their
dainty tints, their soft and sinuous graces, their delicate decision of
character, were exceedingly happy in the stipple-engraver’s hands.
In colour the prints had a charm of reticence which was peculiarly
persuasive. Several of the most engaging were done by the artistic
Condé, such at Mrs. Bouverie, Mrs. Tickell, Mrs. Jackson, Mrs.
Fitzherbert, Mrs. Robinson as “Melania”, and the beautiful youth
Horace Beckford; J. S. Agar did delicately Harriet, Lady Cockerell, as
a Gipsy Woman, Lady Heathcote, and Mrs. Duff; Cardon, with his
distinguished touch, engraved the charming Madame Récamier,
Schiavonetti the Mrs. Maria Cosway and Michel and Isabella
Oginesy, Bartolozzi the Mrs. Harding, Mariano Bovi the Lady Diana
Sinclair, and Charles White the pretty Infancy (Lord Radnor’s
children). Only less fashionable than Cosway’s were the miniatures
of Samuel Shelley. In portrait-manner, and in fanciful composition,
Reynolds was his model and inspiration, but the result, in spite of
high finish and a certain charm of elegance, was a very little
Reynolds, for Shelley’s drawing generally left something for criticism.
Naturally, miniature-painting found happy interpretation in coloured
stipple, and Shelley was fortunate in his engravers, especially
Caroline Watson, with her exquisite delicacy and brilliantly minute
finish, and William Nutter, who was equally at home with the styles of
many painters.
An artist whose dainty and original manner of portraiture, enjoying a
great vogue in its day, was also particularly well suited to the tinted
stipple was John Downman. A man of interesting personality and
individual talent, he began, as a pupil and favourite of Benjamin
West, to take himself seriously and ambitiously as an “historical
painter,” to borrow a definition of the period. Indeed, after he had
won a fashionable reputation for the singular charm and style of his
portraits, and become an A.R.A., we find a contemporary critic of the
Royal Academy exhibition of 1796 confessing surprise at seeing a
scriptural subject painted with such exceptional care and simplicity of
expression by “a hand accustomed to delineate the polished and
artificial beauties of a great metropolis.” But it was to these portrait-
drawings that the artist owed his popularity, and these and the
engravings of them, neglected for three-quarters of a century, are the
things that to-day make Downman a name to conjure with among
collectors. His portraits, exceptionally happy in their suggestion of
spontaneous impression and genial intuition of character, were
drawn with pencil, or with finely-pointed black chalk or charcoal. The
light tinting of hair, cheeks, lips and eyes, with the more definite
colouring, in the case of the female portraits, of an invariable sash
and ribbon on a white dress, was effected in a manner peculiar to
himself. Instead of the usual way, the colour was put on the back of
the drawing, and showed through the specially thin paper he used
with softened effect. How he happened upon this method of tinting
his drawings is rather a romantic story. Seized by the press-gang
and taken to sea, about the beginning of the American War of
Independence, he was kept abroad for nearly two years, and when,
at last, he managed to return to England he found his wife and
children in a state of destitution at Cambridge. There his happy gift of
portraiture brought him a livelihood. One day he left by chance a
drawing face downward upon the table, and one of his children
began daubing some pink paint on what was seemingly a blank
piece of paper. Downman, finding his drawing with daubs upon the
back, perceived delicate tints upon the face, and so he looked with a
discoverer’s eye, and thought the thing out; and the novel way he
had accidentally found of transparently tinting his drawings proved
his way to prosperity. It introduced him into the houses of the socially
great to the royal palace even, and the fashionable beauties of the
day, as well as those who would have liked to be fashionable
beauties, and the favourite actresses, all readily offered their
countenances to Downman’s charming pencil, knowing it would lend
them the air of happy young girls. Of course there was a willing
market for prints from these gladsome and novel presentations of
faces which the people seemed never to tire of; so among the
collector’s prizes to-day are the Mrs. Siddons by Tomkins, the
Duchess of Devonshire and the Viscountess Duncannon by
Bartolozzi, Lady Elizabeth Foster by Caroline Watson, Miss Farren
(Countess of Derby) by Collyer, and Frances Kemble by John Jones.
The social reign of the Court beauties lasted over a long period, and
survived many changes of fashion, from the macaroni absurdities
and monstrous headdresses to the simple muslin gown and the
straw “picture” hat. The days of “those goddesses the Gunnings”
seemed to have come again when the three rival Duchesses,
Devonshire, Rutland, and Gordon, were the autocrats of “the ton,”
ruling the modish world not only with the sovereignty of their beauty,
elegance, wit and charm, but with the fascinating audacity of their
innovations and the outvieing heights of their feathers.

“Come, Paris, leave your hills and dells,


You’ll scorn your dowdy goddesses,
If you once see our English belles,
For all their gowns and boddices.
Here’s Juno Devon all sublime;
Minerva Gordon’s wit and eyes;
Sweet Rutland, Venus in her prime;
You’ll die before you give the prize.”

So sang the enthusiastic poet; though the “satirical rogues” who


wrote squibs and drew caricatures were not quite so kind, and a
writer in the “Morning Post,” with a whimsical turn for statistics,
actually drew up a “Scale of Bon Ton,” showing, in a round dozen of
the leading beauties of the day the relative proportions in which they
possessed beauty, figure, elegance, wit, sense, grace, expression,
sensibility, and principles. It is an amusing list, in which we find the
lovely Mrs. Crewe, for instance, credited with almost the maximum
for beauty, but no grace at all; the Countess of Jersey with plenty of
beauty, grace and expression, but neither sense nor principles; the
Duchess of Devonshire with more principles than beauty, and more
figure than either; her Grace of Gordon with her elegance at zero,
and the Countess of Barrymore supreme in all the feminine
attractions.
When personal gossip about these fashionable beauties was
rampant upon every tongue; when the first appearance of one of
them in a new mode was enough to ensure her being enviously or
admiringly mobbed in the Mall, naturally the portrait-prints in colour
responded to the general curiosity. But there was a public which,
having other pictorial fancies than portraiture, even pretty faces
could not satisfy without the association of sentiment and story. So
there were painters who, recognising this, furnished the engravers
with the popular subject-picture. It was well for their link with
posterity that they did so, for how many of them would be
remembered to-day were it not for these prints? One of the most
prominent was William Redmore Bigg, who won a great popularity by
painting, with the imagination of a country parson, simple incidents of
rustic and domestic life, charged with the most obvious sentiment.
The people took these pictures to their hearts, and they were a gold-
mine to the engravers. As to their artistic qualities we have little
opportunity of judging to-day except through the familiar prints.
These are innumerable, and they all have a conventional prettiness.
In colours the most pleasing, perhaps, are the Saturday Morning of
Burke, the Saturday Evening and Sunday Morning of Nutter; Dulce
Domum and Black Monday of John Jones; Romps and Truants of
William Ward; Shelling Peas and The Hop Picker of Tomkins;
College Breakfast, College Supper, and Rural Misfortunes of
Ogborne, The Sailor Boy’s Return and The Shipwrecked Sailor Boy
of Gaugain.
Then there was William Hamilton, a prolific and prevalent artist. Sent
to Italy in his youth by Robert Adam, the architect, he returned with a
sort of Italianate style of storied design, classical, historical,
allegorical, conventional; but, happily, he developed a light, pretty
and decorative manner of treating simple familiar subjects, which
was pleasing alike to engravers and public. The charming plates
from Thomson’s Seasons, engraved by Tomkins and Bartolozzi; the
graceful set of The Months by Bartolozzi and Gardiner; the idyllic
Morning and Evening by Tomkins, with Noon and Night by Delattre,
the numerous designs of children at play, such as Summer’s
Amusement, Winter’s Amusement, How Smooth, Brother! feel again,
The Castle in Danger, by Gaugain; Breaking-up and The
Masquerade by Nutter; Blind Man’s Buff and Sea-Saw, Children
feeding Fowls, Children playing with a Bird, by Knight; Playing at Hot
Cockles, and others by Bartolozzi: these are among the prettiest
colour-prints of the period and the most valued to-day—especially
The Months. Hamilton’s work just synchronised with the popular
vogue for the coloured stipple, and without these prints how much
should we know of an artist so esteemed in his day, and so
industrious? One might almost ask the same of Francis Wheatley,
whose popularity also survives but through the engraver’s medium. It
was only after his return from Dublin, where he might have continued
to the end as a prosperous portrait-painter had not Dublin society
discovered that the lady it had welcomed as Mrs. Wheatley was
somebody else’s wife, that Wheatley began painting those idealised
urban, rustic, and domestic subjects, which gave him such
contemporary vogue and led to his prompt admission among the
Royal Academicians. Had he never painted anything else he would
always be remembered by his thirteen Cries of London, published by
Colnaghi at intervals between 1793 and 1797, and so familiar to us
through the accomplished copper-plates of the Schiavonetti brothers,
Vendramini, Gaugain and Cardon, though, alas! so wretchedly
hackneyed through the innumerable paltry reproductions. But what a
fascinating, interesting set of prints it is! How redolent of old
lavender! How clean, serene, and country-town-like the London
streets appear; how sweet and fragrant they seem to smell; how
idyllic the life in them! As one looks at these prints one can almost
fancy one hears the old cries echoing through those quiet Georgian
streets. Perhaps the London streets of 1795 were not quite so dainty
as Wheatley’s sympathetic pencil makes them look to have been.
But, remember, that in those days lovely ladies in muslin frocks and
printed calicoes of the new fashion, who had sat to Reynolds, and
whose portraits were in the print-shop windows, were still being
carried in the leisurely sedan-chair, and there were many pretty airs
and graces to be seen; while in those streets, too, the youthful
Turner was seeing atmosphere and feeling his graphic way to
immortality, and young Charles Lamb was walking about, “lending
his heart with usury” to all the humanity he saw in those very streets
which these Wheatley prints keep so fragrant. Of the numberless
other colour-prints after Wheatley perhaps the most valued to-day
are, in mezzotint, The Disaster, The Soldier’s Return and The
Sailor’s Return, by William Ward, The Smitten Clown, by S. W.
Reynolds; in stipple, the Summer and Winter of the Bartolozzi
“Season” set, of which Westall did the Spring and Autumn; The
Cottage Door and The School Door, by Keating; Setting out to the
Fair and The Fairings, by J. Eginton, and the pretty Little Turkey
Cock by Delattre, all admirable examples of the kind of art that made
Wheatley’s reputation.
The pleasant uninspired rusticities and sentimentalities of Henry
Singleton were to popular as to engage the abilities of some of the
leading engravers, who must certainly have made the best of them
for the colour-printer, since Singleton’s colouring was accounted
poor even in his own day. Among the most taking examples we have
Nutter’s pretty pair The Farmyard and The Ale-house Door, Burke’s
Vicar of the Parish, Eginton’s Ballad-Singer, Knight’s British Plenty
and Scarcity in India, some children subjects by Meadows and
Benedetti, and E. Scott’s Lingo and Cowslip, which shows that
genuinely comic actor, John Edwin, and that audaciously eccentric
and adventurous actress, Mrs. Wells, in O’Keefe’s notorious
Haymarket farce, “The Agreeable Surprise,” a group which
Downman also pictured, though with infinitely more spirit and
character.

You might also like