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

Programming Principles and Practice

Using C 3rd Edition Stroustrup


Visit to download the full and correct content document:
https://textbookfull.com/product/programming-principles-and-practice-using-c-3rd-editi
on-stroustrup/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Programming: Principles and Practice Using C++ , Second


Edition Stroustrup

https://textbookfull.com/product/programming-principles-and-
practice-using-c-second-edition-stroustrup/

Programming Principles and Practice Using C Third


Edition Bjarne Stroustrup

https://textbookfull.com/product/programming-principles-and-
practice-using-c-third-edition-bjarne-stroustrup/

A Tour of C 3rd Edition Stroustrup B.

https://textbookfull.com/product/a-tour-of-c-3rd-edition-
stroustrup-b/

Tour of C A C In Depth Series 3rd Edition Stroustrup

https://textbookfull.com/product/tour-of-c-a-c-in-depth-
series-3rd-edition-stroustrup/
A Tour of C++ Stroustrup

https://textbookfull.com/product/a-tour-of-c-stroustrup/

A Tour of C++ Stroustrup

https://textbookfull.com/product/a-tour-of-c-stroustrup-2/

Introduction to Computation and Programming Using


Python 3rd Edition John V. Guttag

https://textbookfull.com/product/introduction-to-computation-and-
programming-using-python-3rd-edition-john-v-guttag/

Introduction to Computation and Programming Using


Python 3rd Edition John V. Guttag

https://textbookfull.com/product/introduction-to-computation-and-
programming-using-python-3rd-edition-john-v-guttag-2/

Principles and Practice of Radiation Oncology 7th


Edition Edward C. Halperin

https://textbookfull.com/product/principles-and-practice-of-
radiation-oncology-7th-edition-edward-c-halperin/
About This eBook
ePUB is an open, industry-standard format for eBooks.
However, support of ePUB and its many features varies
across reading devices and applications. Use your device or
app settings to customize the presentation to your liking.
Settings that you can customize often include font, font size,
single or double column, landscape or portrait mode, and
figures that you can click or tap to enlarge. For additional
information about the settings and features on your reading
device or app, visit the device manufacturer’s Web site.
Many titles include programming code or configuration
examples. To optimize the presentation of these elements,
view the eBook in single-column, landscape mode and
adjust the font size to the smallest setting. In addition to
presenting code and configurations in the reflowable text
format, we have included images of the code that mimic the
presentation found in the print book; therefore, where the
reflowable format may compromise the presentation of the
code listing, you will see a “Click here to view code image”
link. Click the link to view the print-fidelity code image. To
return to the previous page viewed, click the Back button on
your device or app.
Programming: Principles
and Practice Using C++

Third Edition

Bjarne Stroustrup

Hoboken, New Jersey


Cover photo by Photowood Inc./Corbis.
Author photo courtesy of Bjarne Stroustrup.
Page 294: “Promenade a Skagen” by Peder Severin Kroyer.
Page 308: Photo of NASA’s Ingenuity Mars Helicopter, The
National Aeronautics and Space Administration (NASA).
Page 354: Photo of Hurricane Rita as seen from space, The
National Oceanic and Atmospheric Administration (NOAA).

Many of the designations used by manufacturers and sellers


to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and the
publisher was aware of a trademark claim, the designations
have been printed with initial capital letters or in all capitals.

The author and publisher have taken care in the preparation


of this book, but make no expressed or implied warranty of
any kind and assume no responsibility for errors or
omissions. No liability is assumed for incidental or
consequential damages in connection with or arising out of
the use of the information or programs contained herein.

For information about buying this title in bulk quantities, or


for special sales opportunities (which may include electronic
versions; custom cover designs; and content particular to
your business, training goals, marketing focus, or branding
interests), please contact our corporate sales department at
corpsales@pearsoned.com or (800) 382-3419.

For government sales inquiries, please contact


governmentsales@pearsoned.com.
For questions about sales outside the U.S., please contact
intlcs@pearson.com.

Visit us on the Web: informit.com/aw

Library of Congress Control Number: 2024932369

Copyright 2024 by Pearson Education, Inc.

All rights reserved. This publication is protected by


copyright, and permission must be obtained from the
publisher prior to any prohibited reproduction, storage in a
retrieval system, or transmission in any form or by any
means, electronic, mechanical, photocopying, recording, or
likewise. For information regarding permissions, request
forms and the appropriate contacts within the Pearson
Education Global Rights & Permissions Department, please
visit www.pearson.com/permissions.

This book was typeset in Times and Helvetica by the author.

ISBN-13: 978-0-13-830868-1
ISBN-10: 0-13-83086-3
First printing, May 2024
$PrintCode
Contents

Preface

0 Notes to the Reader


0.1 The structure of this book
0.2 A philosophy of teaching and learning
0.3 ISO standard C++
0.4 PPP support
0.5 Author biography
0.6 Bibliography

Part I: The Basics

1 Hello, World!
1.1 Programs
1.2 The classic first program
1.3 Compilation
1.4 Linking
1.5 Programming environments

2 Objects, Types, and Values


2.1 Input
2.2 Variables
2.3 Input and type
2.4 Operations and operators
2.5 Assignment and initialization
2.6 Names
2.7 Types and objects
2.8 Type safety
2.9 Conversions
2.10 Type deduction: auto

3 Computation
3.1 Computation
3.2 Objectives and tools
3.3 Expressions
3.4 Statements
3.5 Functions
3.6 vector
3.7 Language features

4 Errors!
4.1 Introduction
4.2 Sources of errors
4.3 Compile-time errors
4.4 Link-time errors
4.5 Run-time errors
4.6 Exceptions
4.7 Avoiding and finding errors

5 Writing a Program
5.1 A problem
5.2 Thinking about the problem
5.3 Back to the calculator!
5.4 Back to the drawing board
5.5 Turning a grammar into code
5.6 Trying the first version
5.7 Trying the second version
5.8 Token streams
5.9 Program structure

6 Completing a Program
6.1 Introduction
6.2 Input and output
6.3 Error handling
6.4 Negative numbers
6.5 Remainder: %
6.6 Cleaning up the code
6.7 Recovering from errors
6.8 Variables

7 Technicalities: Functions, etc.


7.1 Technicalities
7.2 Declarations and definitions
7.3 Scope
7.4 Function call and return
7.5 Order of evaluation
7.6 Namespaces
7.7 Modules and headers

8 Technicalities: Classes, etc.


8.1 User-defined types
8.2 Classes and members
8.3 Interface and implementation
8.4 Evolving a class: Date
8.5 Enumerations
8.6 Operator overloading
8.7 Class interfaces
Part II: Input and Output

9 Input and Output Streams


9.1 Input and output
9.2 The I/O stream model
9.3 Files
9.4 I/O error handling
9.5 Reading a single value
9.6 User-defined output operators
9.7 User-defined input operators
9.8 A standard input loop
9.9 Reading a structured file
9.10 Formatting
9.11 String streams

10 A Display Model
10.1 Why graphics?
10.2 A display model
10.3 A first example
10.4 Using a GUI library
10.5 Coordinates
10.6 Shapes
10.7 Using Shape primitives
10.8 Getting the first example to run

11 Graphics Classes
11.1 Overview of graphics classes
11.2 Point and Line
11.3 Lines
11.4 Color
11.5 Line_style
11.6 Polylines
11.7 Closed shapes
11.8 Text
11.9 Mark
11.10 Image

12 Class Design
12.1 Design principles
12.2 Shape
12.3 Base and derived classes
12.4 Other Shape functions
12.5 Benefits of object-oriented programming

13 Graphing Functions and Data


13.1 Introduction
13.2 Graphing simple functions
13.3 Function
13.4 Axis
13.5 Approximation
13.6 Graphing data

14 Graphical User Interfaces


14.1 User-interface alternatives
14.2 The “Next” button
14.3 A simple window
14.4 Button and other Widgets
14.5 An example: drawing lines
14.6 Simple animation
14.7 Debugging GUI code

Part III: Data and Algorithms


15 Vector and Free Store
15.1 Introduction
15.2 vector basics
15.3 Memory, addresses, and pointers
15.4 Free store and pointers
15.5 Destructors
15.6 Access to elements
15.7 An example: lists
15.8 The this pointer

16 Arrays, Pointers, and References


16.1 Arrays
16.2 Pointers and references
16.3 C-style strings
16.4 Alternatives to pointer use
16.5 An example: palindromes

17 Essential Operations
17.1 Introduction
17.2 Access to elements
17.3 List initialization
17.4 Copying and moving
17.5 Essential operations
17.6 Other useful operations
17.7 Remaining Vector problems
17.8 Changing size
17.9 Our Vector so far

18 Templates and Exceptions


18.1 Templates
18.2 Generalizing Vector
18.3 Range checking and exceptions
18.4 Resources and exceptions
18.5 Resource-management pointers

19 Containers and Iterators


19.1 Storing and processing data
19.2 Sequences and iterators
19.3 Linked lists
19.4 Generalizing Vector yet again
19.5 An example: a simple text editor
19.6 vector, list, and string

20 Maps and Sets


20.1 Associative containers
20.2 map
20.3 unordered_map
20.4 Timing
20.5 set
20.6 Container overview
20.7 Ranges and iterators

21 Algorithms
21.1 Standard-library algorithms
21.2 Function objects
21.3 Numerical algorithms
21.4 Copying
21.5 Sorting and searching

Index
Preface

Damn the
torpedoes!
Full speed ahead.
– Admiral
Farragut

Programming is the art of expressing solutions to problems


so that a computer can execute those solutions. Much of the
effort in programming is spent finding and refining solutions.
Often, a problem is only fully understood through the
process of programming a solution for it.
This book is for someone who has never programmed
before but is willing to work hard to learn. It helps you
understand the principles and acquire the practical skills of
programming using the C++ programming language. It can
also be used by someone with some programming
knowledge who wants a more thorough grounding in
programming principles and contemporary C++.
Why would you want to program? Our civilization runs on
software. Without understanding software, you are reduced
to believing in “magic” and will be locked out of many of the
most interesting, profitable, and socially useful technical
fields of work. When I talk about programming, I think of the
whole spectrum of computer programs from personal
computer applications with GUIs (graphical user interfaces),
through engineering calculations and embedded systems
control applications (such as digital cameras, cars, and cell
phones), to text manipulation applications as found in many
humanities and business applications. Like mathematics,
programming – when done well – is a valuable intellectual
exercise that sharpens our ability to think. However, thanks
to feedback from the computer, programming is more
concrete than most forms of math and therefore accessible
to more people. It is a way to reach out and change the
world – ideally for the better. Finally, programming can be
great fun.
There are many kinds of programming. This book aims to
serve those who want to write nontrivial programs for the
use of others and to do so responsibly, providing a decent
level of system quality. That is, I assume that you want to
achieve a level of professionalism. Consequently, I chose
the topics for this book to cover what is needed to get
started with real-world programming, not just what is easy
to teach and learn. If you need a technique to get basic
work done right, I describe it, demonstrate concepts and
language facilities needed to support the technique, and
provide exercises for it. If you just want to understand toy
programs or write programs that just call code provided by
others, you can get along with far less than I present. In
such cases, you will probably also be better served by a
language that’s simpler than C++. On the other hand, I
won’t waste your time with material of marginal practical
importance. If an idea is explained here, it’s because you’ll
almost certainly need it.
Programming is learned by writing programs. In this,
programming is similar to other endeavors with a practical
component. You cannot learn to swim, to play a musical
instrument, or to drive a car just from reading a book – you
must practice. Nor can you become a good programmer
without reading and writing lots of code. This book focuses
on code examples closely tied to explanatory text and
diagrams. You need those to understand the ideals,
concepts, and principles of programming and to master the
language constructs used to express them. That’s essential,
but by itself, it will not give you the practical skills of
programming. For that, you need to do the exercises and
get used to the tools for writing, compiling, and running
programs. You need to make your own mistakes and learn to
correct them. There is no substitute for writing code.
Besides, that’s where the fun is!
There is more to programming – much more – than
following a few rules and reading the manual. This book is
not focused on “the syntax of C++.” C++ is used to
illustrate fundamental concepts. Understanding the
fundamental ideals, principles, and techniques is the
essence of a good programmer. Also, “the fundamentals”
are what last: they will still be essential long after today’s
programming languages and tools have evolved or been
replaced.
Code can be beautiful as well as useful. This book is
written to help you to understand what it means for code to
be beautiful, to help you to master the principles of creating
such code, and to build up the practical skills to create it.
Good luck with programming!

Previous Editions
The third edition of Programming: Principles and Practice
Using C++ is about half the size of the second edition.
Students having to carry the book will appreciate the lighter
weight. The reason for the reduced size is simply that more
information about C++ and its standard library is available
on the Web. The essence of the book that is generally used
in a course in programming is in this third edition (“PPP3”),
updated to C++20 plus a bit of C++23. The fourth part of
the previous edition (“PPP2”) was designed to provide extra
information for students to look up when needed and is
available on the Web:

Chapter 1: Computers, People, and Programming


Chapter 11: Customizing Input and Output
Chapter 22: Ideas and History
Chapter 23 Text Manipulation
Chapter 24: Numerics
Chapter 25: Embedded Systems Programming
Chapter 26: Testing
Chapter 27: The C Programming Language
Glossary

Where I felt it useful to reference these chapters, the


references look like this: PPP2.Ch22 or PPP2.§27.1.

Acknowledgments
Special thanks to the people who reviewed drafts of this
book and suggested many improvements: Clovis L. Tondo,
Jose Daniel Garcia Sanchez, J.C. van Winkel, and Ville
Voutilainen. Also, Ville Voutilainen did the non-trivial
mapping of the GUI/Graphics interface library to Qt, making
it portable to an amazing range of systems.
Also, thanks to the many people who contributed to the
first and second editions of this book. Many of their
comments are reflected in this third edition.
0

Notes to the Reader

eiπ + 1
– Leonhard Euler

This chapter is a grab bag of information; it aims to give you an idea of


what to expect from the rest of the book. Please skim through it and
read what you find interesting. Before writing any code, read “PPP
support” (§0.4). A teacher will find most parts immediately useful. If
you are reading this book as a novice, please don’t try to understand
everything. You may want to return and reread this chapter once you
feel comfortable writing and executing small programs.

§0.1 The structure of this book


General approach; Drills, exercises, etc.; What comes after this
book?
§0.2 A philosophy of teaching and learning
A note to students; A note to teachers
§0.3 ISO standard C++
Portability; Guarantees; A brief history of C++
§0.4 PPP support
Web resources
§0.5 Author biography
§0.6 Bibliography
0.1 The structure of this book
This book consists of three parts:

Part I (Chapter 1 to Chapter 8) presents the fundamental concepts and


techniques of programming together with the C++ language and library
facilities needed to get started writing code. This includes the type system,
arithmetic operations, control structures, error handling, and the design,
implementation, and use of functions and user-defined types.
Part II (Chapter 9 to Chapter 14) first describes how to get numeric and
text data from the keyboard and from files, and how to produce
corresponding output to the screen and to files. Then, we show how to
present numeric data, text, and geometric shapes as graphical output, and
how to get input into a program from a graphical user interface (GUI). As
part of that, we introduce the fundamental principles and techniques of
object-oriented programming.
Part III (Chapter 15 to Chapter 21) focuses on the C++ standard library’s
containers and algorithms framework (often referred to as the STL). We
show how containers (such as vector, list, and map) are implemented and
used. In doing so, we introduce low-level facilities such as pointers, arrays,
and dynamic memory. We also show how to handle errors using exceptions
and how to parameterize our classes and functions using templates. As
part of that, we introduce the fundamental principles and techniques of
generic programming. We also demonstrate the design and use of
standard-library algorithms (such as sort, find, and inner_product).

The order of topics is determined by programming techniques, rather than


programming language features.
CC
To ease review and to help you if you miss a key point during a first reading
where you have yet to discover which kind of information is crucial, we place
three kinds of “alert markers” in the margin:

CC: concepts and techniques (this paragraph is an example of that)


AA: advice
XX: warning

The use of CC, AA, and XX, rather than a single token in different colors, is to
help where colors are not easy to distinguish.

0.1.1 General approach


In this book, we address you directly. That is simpler and clearer than the
conventional “professional” indirect form of address, as found in most
scientific papers. By “you” we mean “you, the reader,” and by “we” we mean
“you, the author, and teachers,” working together through a problem, as we
might have done had we been in the same room. I use "I" when I refer to my
own work or personal opinions.
AA
This book is designed to be read chapter by chapter from the beginning to
the end. Often, you’ll want to go back to look at something a second or a third
time. In fact, that’s the only sensible approach, as you’ll always dash past
some details that you don’t yet see the point in. In such cases, you’ll
eventually go back again. Despite the index and the cross-references, this is
not a book that you can open to any page and start reading with any
expectation of success. Each section and each chapter assume understanding
of what came before.
Each chapter is a reasonably self-contained unit, meant to be read in “one
sitting” (logically, if not always feasible on a student’s tight schedule). That’s
one major criterion for separating the text into chapters. Other criteria include
that a chapter is a suitable unit for drills and exercises and that each chapter
presents some specific concept, idea, or technique. This plurality of criteria
has left a few chapters uncomfortably long, so please don’t take “in one
sitting” too literally. In particular, once you have thought about the review
questions, done the drill, and worked on a few exercises, you’ll often find that
you have to go back to reread a few sections.
A common praise for a textbook is “It answered all my questions just as I
thought of them!” That’s an ideal for minor technical questions, and early
readers have observed the phenomenon with this book. However, that cannot
be the whole ideal. We raise questions that a novice would probably not think
of. We aim to ask and answer questions that you need to consider when
writing quality software for the use of others. Learning to ask the right (often
hard) questions is an essential part of learning to think as a programmer.
Asking only the easy and obvious questions would make you feel good, but it
wouldn’t help make you a programmer.
We try to respect your intelligence and to be considerate about your time. In
our presentation, we aim for professionalism rather than cuteness, and we’d
rather understate a point than hype it. We try not to exaggerate the
importance of a programming technique or a language feature, but please
don’t underestimate a simple statement like “This is often useful.” If we quietly
emphasize that something is important, we mean that you’ll sooner or later
waste days if you don’t master it.
Our use of humor is more limited than we would have preferred, but
experience shows that people’s ideas of what is funny differ dramatically and
that a failed attempt at humor can be confusing.
CC
We do not pretend that our ideas or the tools offered are perfect. No tool,
library, language, or technique is “the solution” to all of the many challenges
facing a programmer. At best, a language can help you to develop and express
your solution. We try hard to avoid “white lies”; that is, we refrain from
oversimplified explanations that are clear and easy to understand, but not true
in the context of real languages and real problems.

0.1.2 Drills, exercises, etc


AA
Programming is not just an intellectual activity, so writing programs is
necessary to master programming skills. We provide three levels of
programming practice:

Drills: A drill is a very simple exercise devised to develop practical, almost


mechanical skills. A drill usually consists of a sequence of modifications of
a single program. You should do every drill. A drill is not asking for deep
understanding, cleverness, or initiative. We consider the drills part of the
basic fabric of the book. If you haven’t done the drills, you have not
“done” the book.
Exercises: Some exercises are trivial, and others are very hard, but most
are intended to leave some scope for initiative and imagination. If you are
serious, you’ll do quite a few exercises. At least do enough to know which
are difficult for you. Then do a few more of those. That’s how you’ll learn
the most. The exercises are meant to be manageable without exceptional
cleverness, rather than to be tricky puzzles. However, we hope that we
have provided exercises that are hard enough to challenge anybody and
enough exercises to exhaust even the best student’s available time. We do
not expect you to do them all, but feel free to try.
Try this: Some people like to put the book aside and try some examples
before reading to the end of a chapter; others prefer to read ahead to the
end before trying to get code to run. To support readers with the former
preference, we provide simple suggestions for practical work labeled Try
this at natural breaks in the text. A Try this is generally in the nature of a
drill but focused narrowly on the topic that precedes it. If you pass a Try
this without trying it out – maybe because you are not near a computer or
you find the text riveting – do return to it when you do the chapter drill; a
Try this either complements the chapter drill or is a part of it.

In addition, at the end of each chapter we offer some help to solidify what’s
learned:

Review: At the end of each chapter, you’ll find a set of review questions.
They are intended to point you to the key ideas explained in the chapter.
One way to look at the review questions is as a complement to the
exercises: the exercises focus on the practical aspects of programming,
whereas the review questions try to help you articulate the ideas and
concepts. In that, they resemble good interview questions.
Terms: A section at the end of each chapter presents the basic vocabulary
of programming and of C++. If you want to understand what people say
about programming topics and to articulate your own ideas, you should
know what each term means.
Postscript: A paragraph intended to provide some perspective for the
material presented.

In addition, we recommend that you take part in a small project (and more if
time allows for it). A project is intended to produce a complete useful program.
Ideally, a project is done by a small group of people (e.g., three people)
working together (e.g., while progressing through the later chapters of the
book). Most people find such projects the most fun and that they tie
everything together.
CC
Learning involves repetition. Our ideal is to make every important point at
least twice and to reinforce it with exercises.

0.1.3 What comes after this book?


AA
At the end of this book, will you be an expert at programming and at C++? Of
course not! When done well, programming is a subtle, deep, and highly skilled
art building on a variety of technical skills. You should no more expect to
become an expert at programming in four months than you should expect to
become an expert in biology, in math, in a natural language (such as Chinese,
English, or Danish), or at playing the violin in four months – or in half a year, or
a year. What you should hope for, and what you can expect if you approach
this book seriously, is to have a really good start that allows you to write
relatively simple useful programs, to be able to read more complex programs,
and to have a good conceptual and practical background for further work.
The best follow-up to this initial course is to work on a project developing
code to be used by someone else; preferably guided by an experienced
developer. After that, or (even better) in parallel with a project, read either a
professional-level general textbook, a more specialized book relating to the
needs of your project, or a textbook focusing on a particular aspect of C++
(such as algorithms, graphics, scientific computation, finance, or games); see
§0.6.
AA
Eventually, you should learn another programming language. We don’t
consider it possible to be a professional in the realm of software – even if you
are not primarily a programmer – without knowing more than one language.
Why? No large program is written in a single language. Also, different
languages typically differ in the way code is thought about and programs are
constructed. Design techniques, availability of libraries, and the way programs
are built differ, sometimes dramatically. Even when the syntaxes of two
languages are similar, the similarity is typically only skin deep. Performance,
detection of errors, and constraints on what can be expressed typically differ.
This is similar to the ways natural languages and cultures differ. Knowing only
a single language and a single culture implies the danger of thinking that “the
way we do things” is the only way or the only good way. That way
opportunities are missed, and sub-optimal programs are produced. One of the
best ways to avoid such problems is to know several languages (programming
languages and natural languages).

0.2 A philosophy of teaching and learning


What are we trying to help you learn? And how are we approaching the
process of teaching? We try to present the minimal concepts, techniques, and
tools for you to do effective practical programs, including

Program organization
Debugging and testing
Class design
Computation
Function and algorithm design
Graphics (two-dimensional only)
Graphical user interfaces (GUIs)
Files and stream input and output (I/O)
Memory management
Design and programming ideals
The C++ standard library
Software development strategies

To keep the book lighter than the small laptop on which it is written, some
supplementary topics from the second edition are placed on the Web (§0.4.1):

Computers, People, and Programming (PPP2.Ch1)


Ideals and History (PPP2.Ch22)
Text manipulation (incl. Regular expression matching) (PPP2.Ch23)
Numerics (PPP2.Ch24)
Embedded systems programming (PPP2.Ch25)
C-language programming techniques (PPP2.Ch27)

Working our way through the chapters, we cover the programming techniques
called procedural programming (as with the C programming language), data
abstraction, object-oriented programming, and generic programming. The
main topic of this book is programming, that is, the ideals, techniques, and
tools of expressing ideas in code. The C++ programming language is our main
tool, so we describe many of C++’s facilities in some detail. But please
remember that C++ is just a tool, rather than the main topic of this book. This
is “programming using C++,” not “C++ with a bit of programming theory.”
Each topic we address serves at least two purposes: it presents a technique,
concept, or principle and also a practical language or library feature. For
example, we use the interface to a two-dimensional graphics system to
illustrate the use of classes and inheritance. This allows us to be economical
with space (and your time) and also to emphasize that programming is more
than simply slinging code together to get a result as quickly as possible. The
C++ standard library is a major source of such “double duty” examples –
many even do triple duty. For example, we introduce the standard-library
vector, use it to illustrate widely useful design techniques, and show many of
the programming techniques used to implement it. One of our aims is to show
you how major library facilities are implemented and how they map to
hardware. We insist that craftsmen must understand their tools, not just
consider them “magical.”
Some topics will be of greater interest to some programmers than to others.
However, we encourage you not to prejudge your needs (how would you know
what you’ll need in the future?) and at least look at every chapter. If you read
this book as part of a course, your teacher will guide your selection.
CC
We characterize our approach as “depth-first.” It is also “concrete-first” and
“concept-based.” First, we quickly (well, relatively quickly, Chapter 1 to
Chapter 9) assemble a set of skills needed for writing small practical programs.
In doing so, we present a lot of tools and techniques in minimal detail. We
focus on simple concrete code examples because people grasp the concrete
faster than the abstract. That’s simply the way most humans learn. At this
initial stage, you should not expect to understand every little detail. In
particular, you’ll find that trying something slightly different from what just
worked can have “mysterious” effects. Do try, though! Please do the drills and
exercises we provide. Just remember that early on you just don’t have the
concepts and skills to accurately estimate what’s simple and what’s
complicated; expect surprises and learn from them.
AA
We move fast in this initial phase – we want to get you to the point where
you can write interesting programs as fast as possible. Someone will argue,
“We must move slowly and carefully; we must walk before we can run!” But
have you ever watched a baby learning to walk? Babies really do run by
themselves before they learn the finer skills of slow, controlled walking.
Similarly, you will dash ahead, occasionally stumbling, to get a feel of
programming before slowing down to gain the necessary finer control and
understanding. You must run before you can walk!
XX
It is essential that you don’t get stuck in an attempt to learn “everything”
about some language detail or technique. For example, you could memorize all
of C++’s built-in types and all the rules for their use. Of course you could, and
doing so might make you feel knowledgeable. However, it would not make you
a programmer. Skipping details will get you “burned” occasionally for lack of
knowledge, but it is the fastest way to gain the perspective needed to write
good programs. Note that our approach is essentially the one used by children
learning their native language and also the most effective approach used to
learn a foreign language. We encourage you to seek help from teachers,
friends, colleagues, Mentors, etc. on the inevitable occasions when you are
stuck. Be assured that nothing in these early chapters is fundamentally
difficult. However, much will be unfamiliar and might therefore feel difficult at
first.
Later, we build on your initial skills to broaden your base of knowledge. We
use examples and exercises to solidify your understanding, and to provide a
conceptual base for programming.
AA
We place a heavy emphasis on ideals and reasons. You need ideals to guide
you when you look for practical solutions – to know when a solution is good
and principled. You need to understand the reasons behind those ideals to
understand why they should be your ideals, why aiming for them will help you
and the users of your code. Nobody should be satisfied with “because that’s
the way it is” as an explanation. More importantly, an understanding of ideals
and reasons allows you to generalize from what you know to new situations
and to combine ideas and tools in novel ways to address new problems.
Knowing “why” is an essential part of acquiring programming skills.
Conversely, just memorizing lots of poorly understood rules is limiting, a
source of errors, and a massive waste of time. We consider your time precious
and try not to waste it.
Many C++ language-technical details are banished to other sources, mostly
on the Web (§0.4.1). We assume that you have the initiative to search out
information when needed. Use the index and the table of contents. Don’t
forget the online help facilities of your compiler. Remember, though, to
consider every Web resource highly suspect until you have reason to believe
better of it. Many an authoritative-looking Web site is put up by a
programming novice or someone with something to sell. Others are simply
outdated. We provide a collection of links and information on our support Web
site: www.stroustrup.com/programming.xhtml.
Please don’t be too impatient for “realistic” examples. Our ideal example is
the shortest and simplest code that directly illustrates a language facility, a
concept, or a technique. Most real-world examples are far messier than ours,
yet do not consist of more than a combination of what we demonstrate.
Successful commercial programs with hundreds of thousands of lines of code
are based on techniques that we illustrate in a dozen 50-line programs. The
fastest way to understand real-world code is through a good understanding of
the fundamentals.
We do not use “cute examples involving cuddly animals” to illustrate our
points. We assume that you aim to write real programs to be used by real
people, so every example that is not presented as specifically language-
technical is taken from a real-world use. Our basic tone is that of professionals
addressing (future) professionals.
C++ rests on two pillars:

Efficient direct access to machine resources: making C++ effective for


low-level, machine-near, programming as is essential in many application
domains.
Powerful (Zero-overhead) abstraction mechanisms: making it possible to
escape the error-prone low-level programming by providing elegant,
flexible, and type-and-resource-safe, yet efficient facilities needed for
higher-level programming.

This book teaches both levels. We use the implementation of higher-level


abstractions as our primary examples to introduce low-level language features
and programming techniques. The aim is always to write code at the highest
level affordable, but that often requires a foundation built using lower-level
facilities and techniques. We aim for you to master both levels.

0.2.1 A note to students


AA
Many thousands of first-year university students taught using the first two
editions of this book had never before seen a line of code in their lives. Most
succeeded, so you can do it, too.
You don’t have to read this book as part of a course. The book is widely used
for self-study. However, whether you work your way through as part of a
course or independently, try to work with others. Programming has an – unfair
– reputation as a lonely activity. Most people work better and learn faster when
they are part of a group with a common aim. Learning together and discussing
problems with friends is not cheating! It is the most efficient – as well as most
pleasant – way of making progress. If nothing else, working with friends forces
you to articulate your ideas, which is just about the most efficient way of
testing your understanding and making sure you remember. You don’t actually
have to personally discover the answer to every obscure language and
programming environment problem. However, please don’t cheat yourself by
not doing the drills and a fair number of exercises (even if no teacher forces
you to do them). Remember: programming is (among other things) a practical
skill that you must practice to master.
Most students – especially thoughtful good students – face times when they
wonder whether their hard work is worthwhile. When (not if) this happens to
you, take a break, reread this chapter, look at the “Computers, People, and
Programming” and “Ideals and History” chapters posted on the Web (§0.4.1).
There, I try to articulate what I find exciting about programming and why I
consider it a crucial tool for making a positive contribution to the world.
Please don’t be too impatient. Learning any major new and valuable skill
takes time.
The primary aim of this book is to help you to express your ideas in code,
not to teach you how to get those ideas. Along the way, we give many
examples of how we can address a problem, usually through analysis of a
problem followed by gradual refinement of a solution. We consider
programming itself a form of problem solving: only through complete
understanding of a problem and its solution can you express a correct program
for it, and only through constructing and testing a program can you be certain
that your understanding is complete. Thus, programming is inherently part of
an effort to gain understanding. However, we aim to demonstrate this through
examples, rather than through “preaching” or presentation of detailed
prescriptions for problem solving.

0.2.2 A note to teachers


CC
No. This is not a traditional Computer Science 101 course. It is a book about
how to construct working software. As such, it leaves out much of what a
computer science student is traditionally exposed to (Turing completeness,
state machines, discrete math, grammars, etc.). Even hardware is ignored on
the assumption that students have used computers in various ways since
kindergarten. This book does not even try to mention most important CS
topics. It is about programming (or more generally about how to develop
software), and as such it goes into more detail about fewer topics than many
traditional courses. It tries to do just one thing well, and computer science is
not a one-course topic. If this book/course is used as part of a computer
science, computer engineering, electrical engineering (many of our first
students were EE majors), information science, or whatever program, we
expect it to be taught alongside other courses as part of a well-rounded
introduction.
Many students like to get an idea why subjects are taught and why they are
taught in the way they are. Please try to convey my teaching philosophy,
general approach, etc. to your students along the way. Also, to motivate
students, please present short examples of areas and applications where C++
is used extensively, such as aerospace, medicine, games, animation, cars,
finance, and scientific computation.

0.3 ISO standard C++


C++ is defined by an ISO standard. The first ISO C++ standard was ratified in
1998, so that version of C++ is known as C++98. The code for this edition of
the book uses contemporary C++, C++20 (plus a bit of C++23). If your
compiler does not support C++20 [C++20], get a new compiler. Good, modern
C++ compilers can be downloaded from a variety of suppliers; see
www.stroustrup.com/compilers.xhtml. Learning to program using an earlier and less
supportive version of the language can be unnecessarily hard.
On the other hand, you may be in an environment where you are able to
use only C++14 or C++17. Most of the contents of this book will still apply,
but you’ll have trouble with features introduced in C++20:

modules (§7.7.1). Instead of modules use header files (§7.7.2). In particular,


use #include "PPPheaders.h" to compile our examples and your exercises,
rather than #include "PPP.h" (§0.4).
ranges (§20.7). Use explicit iterators, rather than ranges. For example,
rather than ranges::sort(v). If/when that gets tedious,
sort(v.begin(),v.end())
write your own ranges versions of your favorite algorithms (§21.1).
span (§16.4.1). Fall back on the old “pointer and size” technique. For
example, void f(int* p, int n); rather than void f(span<int> s); and do your own
range checking as needed.
concepts (§18.1.3). Use plain template<typename T> and hope for the best.
The error messages from that for simple mistakes can be horrendous.

0.3.1 Portability
CC
It is common to write C++ to run on a variety of machines. Major C++
applications run on machines we haven’t ever heard of! We consider the use of
C++ on a variety of machine architectures and operating systems most
important. Essentially every example in this book is not only ISO Standard
C++, but also portable. By portable, we mean that we make no assumptions
about the computer, the operating system, and the compiler beyond that an
up-to-date standard-conforming C++ implementation is available. Unless
specifically stated, the code we present should work on every C++
Another random document with
no related content on Scribd:
unsettled and uncomfortable. The ship would not keep still. New
complications of ropes and hauling-gear were developed. The capstan in the
waist was manned, and round and round went the sailors, while the deck
they trod was inclined in all manner of uncomfortable angles. Tackle and
great blocks were hooked to ringbolts, and a vast amount of what seemed to
me fruitless hauling went on. Barrels of water swashed over the bulwarks,
knocking us down and drenching us. Wet and shivering we clung to
belaying pins or anything within reach, of no earthly use to anybody,
thinking of the cheerfully lit, well-warmed rooms and comfortable tea-
tables even then set but so few miles away on the shores of Long Island.
When the order came to reef, and I saw the men clambering up the fore and
main rigging, I added myself to their number, though I felt I should never
come down again—at least in one piece. It was my debut aloft off
soundings. Many a time had I clambered about the rigging of the old
whalers as they lay at the village wharf, but they were not roaring, kicking,
and plunging like this vessel. Heavy seamen’s boots kicked me in the face
as I followed their wearers up this awful ascent; other heavy boots trod on
my fingers; they shook the ratlines, too, in a most uncomfortable manner.
The mast strained and groaned fearfully. Somehow, after climbing over
some awful chasms, I got on the yard with the men. I dared not go out far.
The foot rope wobbled, jerked, and gave way under me at times with the
weight and notion of the men upon it. The great sail seemed in no humor to
be furled. It hauled away from us, bellied, puffed, and kept up a gigantic
series of thundering flaps. Laying over on the yard the men would gather in
as much of the hard, wet, wire-like canvas as possible and then together
haul back on it.
This I objected to. It was risky enough to lay out on an enormous stick
sixty feet in the air, while the wind tore our voices from us and seemed to
hurl the words far away ere they had well got out of our mouths, and the
white-topped waves, dimly seen below, seemed leaping up and snatching at
us. But at that height, and amid all that motion, to balance one’s body on the
stomach, grasp with outstretched arms a hard roll of struggling, wet canvas,
while the legs were as far extended the other way and the feet resting only
against a rope working and wobbling and giving way here and there from
the weight of fifteen hundred pounds of men unequally distributed over it,
was a task and seeming risk too great for my courage. I dared do nothing
but hold on. The conduct of the maintopsail was desperate and outrageous.
It seemed straining every nerve—supposing, for the sake of forcible
expression, that it had nerves—to pull us off the yard and “into the great
deep.” I found myself between two old sailors, who lost no time in
convincing me of my complete and utter worthlessness aloft. I concurred.
They bade me clear out and get down on deck. I was glad to do so. Reefing
topsails in reality was very different from reefing them in books or in
imagination. On reaching the deck I concluded to lie down. All through the
evening I had experienced an uneasy sensation in the stomach. I argued
with myself it was not seasickness—something did not agree with me. But
when I lay down in the scuppers I admitted being seasick. Then I only cared
to lie there. Life was too miserable even to hope in. The tumult went on as
ever. The sailors trampled over me. Being in the way, they dragged me
aside. I cared not. Finally some one bawled in my ear, “Sick! go below.” I
went. The five other boys, all similarly affected, all caring naught for life or
living, lay in their bunks.
The boys’ house was about the size of a respectable pig pen—a single
pig pen. There was room in it for two boys to turn at once, providing they
turned slowly and carefully. On going on board we had bestowed such of
our outfit as could be brought into this pen in the manner in which boys of
sixteen bestow things generally on first commencing to “keep house.”
Everything was arranged on a terra firma basis. We made no calculation for
the ship’s deviating from an even keel. When she did commence to pitch
everything fell down. Clothing fell on the floor; plates, knives, forks, cups
and bottles rolled from shelf and bunk; bread, meat, and the molasses kegs
fell; plum and sponge cake, pie and sweetmeats fell; for each boy had a
space in his sea-chest filled with these articles, placed there by kind, dear
relatives at home. It was intended that we should not refer to them until the
ship was far advanced on her voyage. But we never had such large supplies
of cake and sweetmeats at hand before; so we went for these things
immediately. The house abounded with them the first night out. The roof
leaked. We left our sliding-door carelessly open, and a few barrels of the
ocean slopped over the bulwarks into the apartment. At midnight our
combined clothing, plates, mugs, knives, forks, bottles, water-kegs, combs,
hair-brushes, hats, pants, coats, meat, bread, pie, cake, sweetmeats,
molasses, salt water, and an occasional seasick and despairing boy, united to
form a wet, sodden mass on the floor two feet in depth. Above the storm
howled and swept through the rigging, with little sail to interrupt it. Six sick
and wretched boys in their berths lay “heads and pints,” as they pack
herring; that is, the toe of one rested on the pillow of the other, for it was
not possible to lie otherwise in those narrow receptacles for the living. But
the horrors of that second night are not to be related.
No solicitous stewards with basins and tenders of broth and champagne
attended us. We were not cabin passengers on an ocean steamer. Barely had
the next morning’s dawn appeared when our door was flung open. In it
stood that dreadful second mate of the greenish eyes, hard, brick-red
complexion, horny fists and raspy voice—a hard, rough, rude, unfeeling
man, who cried: “Come out of that! Oh, you’re young bears—your troubles
ain’t commenced yet!” Then his long, bony arm gripped us one after the
other and tore us from our bunks. How unlike getting up at home on a cold
winter’s morning, as, snuggling in our warm feather beds, we heard our
mothers call time after time at the foot of the stairs: “Come now, get up!
Breakfast is ready!” And with the delay prone to over-indulged youth, we
still lay abed until the aroma of buckwheat cakes and coffee stealing to our
bedrooms developed an appetite and induced us to rise. Out, this dreadful
morning, we tumbled, in the wet clothes wherein we had lain all night,
weak, sick, staggering, giddy. A long iron hook was put in my hand and I
was desired to go forward and assist in hauling along length after length of
the cable preparatory to stowing it away. Sky and sea were all of dull,
monotonous gray; the ship was still clambering one great wave after an
another with tiresome and laborious monotony. All the canvas of the
preceding day had disappeared, save a much-diminished foretop-sail and
storm staysail. The mates on duty were alert and swearing. The men, not all
fully recovered from their last shore debauch, were grumbling and swearing
also. The cook, a dark-hued tropical mongrel, with glittering eyes, was
swearing at something amiss in his department. It was a miserable time. But
a cure was quickly effected. In thirty-six hours all seasickness had departed.
With the delicate petting process in vogue with wealthy cabin-passengers it
would have required a week. But we had no time in which to be seasick.
Life for us on board this ship was commenced on a new basis. We were
obliged to learn “manners.” Manners among modern youth have become
almost obsolete. The etiquette and formality required from the younger to
the elder, and common to the time of perukes and knee-breeches, has now
little place save on shipboard, where such traditions and customs linger. We
were surprised to find it our duty to say “Sir” to an officer, and also to find
it imperative to recognize every order addressed us by the remark; “Aye,
aye, sir!” The sullen, shambling fashion of receiving words addressed us in
silence, so that the speaker was left in doubt as to whether he was heard or
not, had no place off soundings. In short, we were obliged to practice what
is not common now to many boys on shore—that is, an outward show of
respect for superiors. If business called us to the “West End” of a ship, the
quarter-deck, our place was to walk on the lee side of that deck and leave
the weather side the moment the duty was done. If sent for any article by an
officer, it was our business to find it without further recourse to him.
Petted boys have little patience for hunting for things. At home two
minutes is about the limit of time spent in looking for a mislaid poker, and
then “Ma!” “Pa!” or “Aunt!” is called on to turn to and do this disagreeable
work. The second mate once ordered me to find a certain iron hook,
wherewith to draw the pump boxes, and when, after a short search, I
returned and asked him where it might be I was horrified by the expression
of astonished indignation spreading over his face as he yelled: “Great Scott,
he expects me to help him find it!” I saw the point and all it involved, and
never so wounded an officer’s dignity again. It is a sailor’s, and especially a
boy’s business on shipboard, to find whatever he is ordered to. It must be
produced—no matter whether it’s in the ship or not. At all events that’s the
sentiment regarding the matter. But it is good discipline for boys over-
nursed at home and only physically weaned. The “cold, cold world” would
not, in some cases, be so cold to the newly-fledged youth first trying his
feeble wings outside the family nest, did parents judiciously establish a
little of this maritime usage at home.
We soon learned on the Wizard how well we had lived at home. Our sea
fare of hard tack and salt junk taught us how to appreciate at their true value
the broiled streaks, hot cakes, and buttered toast of home tables. The quart
of very common molasses served out to us weekly soon became a luxury,
and when the steward occasionally brought us “Benavlins” (the nautical
term for the broken fragments from the cabin table), we regarded it as very
luxurious living, though a month previous we should have deemed such
food fit only for the swill-tub.
In about two weeks we had settled down into the routine of life at sea.
Sailors are apt to term theirs a “dog’s life.” I never did. It was a peculiar
life, and in some respects an unpleasant one—like many others on land. But
it was not a “dog’s life.” There was plenty to eat, and we relished our
“lobscouse,” hard tack, salt junk, beans, codfish, potatoes and Sunday’s and
Thursday’s duff. The hours for labor were not exhausting. It was “watch
and watch, four hours off and four hours on.” Many a New York retail
grocer’s clerk, who turns to at 5 in the morning and never leaves off until 11
at night, would revel on such regulation of time and labor. So would many a
sewing-girl. We had plenty of time for sleep. If called up at 4 every
alternate morning, and obliged to stand watch until 8 A.M., we could “turn
in” at that hour after breakfast and sleep till noon. Apart from the alternate
watches the work or “jobs” occupied about six hours per day. True, there
was at times some heavy work, but it was only occasional. Sailor-work is
not heavy as compared with the incessant fagging, wearing, never-ending
character of some occupations on shore. Skill, agility, and quickness are in
greater demand than mere brute strength.
Lobscouse is a preparation of hard bread, first soaked and then stewed
with shredded salt beef. It looks somewhat like rations for a delicate bear
when served out by the panful. But it is very good. Salt beef is wonderfully
improved by streaks of fat through it. These serve the foremast hands in
place of butter. I know of no better relish than good pilot bread and sliced
salt junk, with plenty of clean white fat. On shore that quart of boiling hot
liquid, sweetened with molasses and called tea, would have been pitched
into the gutter. At sea, after an afternoon’s work, it was good. With similar
content and resignation, not to say happiness, we drank in the morning the
hot quart of black fluid similarly sweetened and called coffee. It was not
real coffee. I don’t know what it was. I cared not to know. Of course we
grumbled at it. But we drank it. It was “filling,” and was far better than the
cold, brackish water, impregnated thickly with iron rust, a gallon of which
was served out daily. For the fresh water was kept below in an iron tank,
and, as the deck leaked, a small portion of the Atlantic had somehow gained
admission to it and slightly salted it. It resembled chocolate to the eye, but
not to the palate.
CHAPTER IV.

MUCH WATER AND MUTINY.

On the fourth day out the Wizard was found to have four feet of water in
her hold. The ship was pumped dry in about four hours, when she
proceeded to fill up again. The Captain seemed a man of many minds for
the next two or three days. First the ship was put back for New York. This
course was altered and her bows pointed for Africa. Then the foremast
hands became worried, and going aft one morning in a body, asked Captain
S—— what he meant to do and where he meant to go, because they had
shipped for San Francisco and they did not intend going anywhere else. The
Captain answered, that his own safety and that of the vessel were as dear to
him as their lives were to them, and that he intended doing the best for the
general good. This answer was not very satisfactory to the crew, who went
grumbling back to their quarters. Ultimately it turned out that we were to
take the leak with us to San Francisco. At the rate the water was running in
it was judged that the bone, muscle, and sinews of the crew could manage
to keep it down. So we pumped all the way round Cape Horn. We pumped
during our respective watches every two hours. In good weather and on an
even keel it took half an hour to “suck the pumps.” If the vessel was heeled
to larboard or starboard, it took much longer. In very rough weather we
pumped all the time that could be spared from other duties. There were two
pumps at the foot of the mainmast worked by levers, and these were
furnished with “bell ropes” to pull on. Half the watch worked at each lever,
and these were located exactly where on stormy nights the wild waves were
in the habit of flinging over the bulwarks a hogshead or two of water to
drench us and wash us off our feet.
The Wizard was a very “wet ship.” She loved giving us moist surprises.
Sometimes on a fine day she would gracefully, but suddenly, poke her nose
under, and come up and out of the Atlantic or Pacific ocean with fifteen or
twenty tons of pea-green sea water foaming over the t’gallant forecastle,
cascading thence on the spar deck and washing everything movable slam
bang up and sometimes into the cabin. This took place once on a washday.
Sailors’ washday is often regulated by the supply of water caught from the
clouds. On this particular occasion the fore deck was full of old salts up to
their bared elbows in suds, vigorously discoursing washtub and washboard.
Then the flood came, and in a moment the deck was filled with a great
surge bearing on its crest all these old salts struggling among their tubs,
their washboards, their soap and partly-washed garments. The cabin
bulkhead partly stopped some, but the door being open others were borne
partly inside, and their woollen shirts were afterward found stranded on the
carpeted cabin floor. One “duff day” we had gathered about our extra repast
in the boys’ house. The duff and New Orleans molasses had just
commenced to disappear. Then a shining, greenish, translucent cataract
filled the doorway from top to bottom. It struck boys, beef, bread, duff, and
dishes. It scattered them. It tumbled them in various heaps. It was a brief
season of terror, spitting, and sputtering salt water, and a scrambling for life,
as we thought. It washed under bunks and in remote corners duff, bread,
beef, plates, knives, forks, cups, spoons and molasses-bottles. The dinner
was lost. Going on deck we found a couple of feet of water swashing from
bulwark to bulwark with every roll, bearing with it heavy blocks and
everything movable which had been loosened by the shock, to the great risk
of legs and bodies. But these were trifles. At least we call them trifles when
they are over. I have noticed, however, that a man may swear as hard at a
jammed finger as a broken leg, and the most efficacious means in the world
to quickly develop a furious temper is to lose one’s dinner when hungry, get
wet through, then abused by a Dutch mate for not stirring around quicker,
and finally work all the afternoon setting things to rights on an empty
stomach, robbed and disappointed of its duff. This is no trifle.
Learning the ropes isn’t all a boy’s first lessons at sea. He must learn
also to wash and mend his own clothes. At least he must try to learn and go
through the forms. I never could wash a flannel shirt, and how the
extraneous matter called dirt, which the washing process is intended to
disperse, is gotten rid of by soap and muscle at an equal average over the
entire surface of the garment is for me to-day one of earth’s mysteries. I
could wash a shirt in spots. When I tried to convince myself that I had
finished it I could still see where I had washed clean and where I had not.
There is a certain system in the proper manipulation of a garment in a
washtub which to me is incomprehensible. An old sailor is usually a good
washer. It’s part of his trade. Those on the Wizard would reprove the boys
for their slipshod work. “Such a slovenly washed shirt as that,” said Conner,
an old man-of-war’s man, “hung in the rigging is a disgrace to the ship.” He
alluded to one of mine. The failure was not from any lack of labor put on it.
The trouble lay in that I didn’t know where to put the labor on. It was easier
to tie a shirt to a line, fling it overboard and let it tow. This will wash
clothes—wash all the warp out of them in time. The practice was at last
forbidden the boys on the Wizard. It’s a lazy boy’s wash. The adage “It’s
never too late to mend” is not applicable on shipboard. It should there read
“It’s never too early to mend.” Of course a boy of sixteen, whose mother
has always stitched for him, will allow his clothes to go until they fall off
his body before using his needle. As I did. And I sewed myself up only to
rip asunder immediately. I went about decks a thing of flaps, rips, rags, and
abortive patches, until they called me the ship’s scarecrow. And so would
many another spruce young man under similar discipline. It’s good once in
one’s life to be brought thus low.
It was particularly disagreeable at midnight as we assembled at the bell
ropes to give her the last “shake-up,” and more asleep than awake pulled
wearily with monotonous clank. Sometimes at that hour, when our labors
were half through, the valves would get out of order. It was then necessary
to call the carpenter and have them repaired. This would keep us on deck
half an hour or more, for by mutual compact each watch was obliged to
“suck its own pumps.” Such delays made the men very angry. They stopped
singing at their work—always a bad sign—and became silent, morose, and
sullen. For the first six weeks all the “shanti songs” known on the sea had
been sung. Regularly at each pumping exercise we had “Santy Anna,”
“Bully in the Alley,” “Miranda Lee,” “Storm Along, John,” and other
operatic maritime gems, some of which might have a place in our modern
operas of The Pinafore school. There’s a good deal of rough melody when
these airs are rolled out by twenty or thirty strong lungs to the
accompaniment of a windlass’ clank and the wild, shrill sweep of the winds
in the rigging above. But the men would no longer sing. The fact was
reported to the Captain. He put on his spectacles, walked out on the quarter-
deck and gazed at them mournfully and reprovingly. The mates tried to
incite them to renewed melody. But the shipping articles did not compel
them to sing unless they felt like it. The pumps clanked gloomily without
any enlivening chorus. The Captain went sadly back to his cabin and
renewed his novel.
One night the pumps broke down five minutes before 12 o’clock. Our
watch was at work on them. The carpenter was called as usual, and after the
usual bungling and fishing in the well for the broken valves, they were put
in order again. It was then nearly 1 A.M. Meanwhile all the able seamen in
our watch had at eight bells walked below. The watch newly come on deck
refused to pump the ship clear, alleging it was the business of the others.
The watch below were bidden to come on deck and perform their neglected
duty. They refused. This was mutiny. The four mates got their pistols,
entered the forecastle and stormed, ordered, and threatened. It was of no
avail. The fifteen able seamen who refused constituted the main strength
and effectiveness of that watch. They were threatened with being put in
irons. They preferred irons to pumping out of their turn. They were put in
irons, fifteen stout men, by the four mates, who then returned and reported
proceedings to the Captain. The men remained shackled until the next
morning. It was then discovered that it was impossible to work the ship
without their aid. Of course they couldn’t handle the vessel in irons. In
reality double the number of able men were needed in both watches. The
Wizard rated over 3,000 tons, and many a frigate of her size would have
been deemed poorly off with less than one hundred men for handling the
ship alone. We rarely secured the lower sails properly in heavy weather,
from the mere lack of physical strength to handle them. So Captain S——
pored sadly at his breakfast through his gold-bowed spectacles, and when
the meal was over issued orders for the release of the fifteen men in irons.
In this little affair the boys and ordinary seamen belonging to the mutinous
watch took no part. They were strictly neutral and waited to see which side
would win. I felt rather unpleasant and alarmed. Though not a full-fledged
mutiny and a conversion of a peaceful merchantman into a pirate, it did
look at one time as if the initiatory steps to such end were being taken.
One of the great aims of existence at sea is that of keeping the decks
clean. The scrubbing, swishing, and swashing is performed by each watch
on alternate mornings, and commences at daylight. It was the one ordeal
which I regarded with horror and contempt. You are called up at four in the
morning, when the sleep of a growing youth is soundest. The maniacal
wretch of the other watch, who does the calling, does it with the glee and
screech of a fiend. He will not stop his “All Ha-a-a-nds!” until he hears
some responsive echo from the sleepers. He is noisy and joyous because it
is so near the time he can turn in. And these four hours of sleep at sea are
such luxuries as may rarely be realized on shore. But the mate’s watch is
calling us, screeching, howling, thumping on the forecastle door, and
making himself extremely pleasant. The old sailors being called gradually
rise to sitting postures in their berths with yawns, oaths, and grumblings. If
the hideous caller is seen, a boot or other missile may be shied in that
direction. Otherwise the prejudice and disgust for his clamor on the part of
those called expresses itself in irritable sarcasms such as, “Oh, why don’t
you make a little more noise?” “Think yourself smart, don’t you?” “Say,
don’t you s’pose we can hear?” To-morrow morning at 12 or 4 these
personalities and conditions of mind will be reversed. The awakened
irritable grumbler will be the joyous caller, and the joyous caller of this
early morn will be searching about his bunk for some offensive implement
to hurl at the biped who thus performs the matutinal office of the early
village cock.
We are called and on deck, and stumbling about, maybe with one boot
half on, and more asleep than awake and more dead than alive. We are in
the warm, enervating latitude of the tropics, with every sinew relaxed from
the steaming heat. Perhaps there is a light wind aft. We are carrying
studding-sails. Studding-sails are beautiful to look at from a distance. But
when once you have sailed in a ship carrying them from the royals down
and know something of the labor of rigging them out all on one side, fore,
main, and mizzen-masts, and then, if the breeze alters a couple of points,
taking the starboard sails all down and rigging out the larboard, or perhaps
on both sides—and this on a Sunday afternoon, when there are no jobs and
you’ve been expecting plenty of leisure to eat your duff and molasses; or if
you have ever helped carry those heavy yards about the deck when the ship
was rolling violently in a heavy ground swell, and every time she brought
up, sails, blocks, and everything movable was bringing up also with a series
of pistol-like reports; or if you have ever laid out on a royal yard trying to
pass a heavy rope through the “jewel block,” at the extreme end thereof,
while the mast and yard were oscillating to and fro with you through the air
in a rapidly recurring series of gigantic arcs caused by the lazy swell, in the
trough of which your ship is rolling—and at the end of each roll you find
yourself holding on for dear life, lest at the termination of each oscillation
you be shot like an arrow into the sea from your insecure perch—why in all
these cases the beauty and picturesqueness of a ship under studding-sails
will be tempered by some sober realities.
It is 5:30 or 6 o’clock. The morning light has come. The cry of “Turn
to!” is heard. That is, “turn to” to wash down decks, an operation which will
tax the already exhausted resources of an empty stomach until breakfast
time at 8 o’clock. The mates have their fragrant “cabin coffee” and biscuit
served them on the brass capstan aft; we can smell its aroma, but nothing
warm can get into our stomachs for over two long hours of work. The basic
idea in this regular washing down decks at sea seems to be that of keeping
men busy for the sake of keeping them busy. The top of every deck plank
must be scrubbed with a care and scrutiny befitting the labors of a diamond
polisher on his gems, while the under side may be dripping with foulness,
as it sometimes is. I had the post of honor in scrubbing the quarter-deck.
That was the drawing of water in a canvas bucket from the mizzen chains to
wash over that deck. The remaining five boys would push wearily about
with their brooms, hand-brushes, squabs, and squilgees, superintended by
our extraordinary fourth mate (always to me an object of interest, from the
fact of the secret carefully hoarded in my breast that I had pulled him into
the New York dock), who, with a microscopic eye inspected each crack and
seam after the boys’ labors, in search of atomic particles of dirt, and called
them back with all the dignity of command, and a small amount of
commanding personality behind it, whenever he deemed he had discovered
any. When this labor was finished I was generally so exhausted as to have
no appetite for breakfast. But a sailor’s stomach is not presumed to be at all
sensitive under any conditions. And above all a “boy”—a boy belonging to
a squad of boys who about once a day were encouraged and enthused to
exertion and maritime ambition by the assurance conveyed them by one of
the mates that they weren’t “worth their salt”—what business had a boy’s
stomach to put on airs at sea? Most landsmen if called up at 4 o’clock on a
muggy morning and worked like mules for a couple of hours on a digestive
vacuum, would probably at the breakfast hour feel more the need of food
than the appetite to partake of it.
Though I followed the sea nearly two years, I am no sailor. The net
result of my maritime experience is a capacity for tying a bow-line or a
square knot and a positive knowledge and conviction concerning which end
of the ship goes first. I also know enough not throw hot ashes to windward.
But on a yard I could never do much else but hold on. The foolhardy
men about me would lie out flat on their stomachs amid the darkness and
storm, and expose themselves to the risk of pitching headlong into the sea
in the most reckless manner while trying to “spill the wind” out of a
t’gallant sail. But I never emulated them. I never lived up to the maritime
maxim of “one hand for yourself and the other for the owners.” I kept both
hands for myself, and that kept me from going overboard. What would the
owners have cared had I gone overboard? Nothing. Such an occurrence
twenty-five odd years ago would, weeks afterward, have been reported in
the marine news this way: “Common sailor, very common sailor, fell from
t’gallant yard off Cape Horn and lost.” The owner would have secretly
rejoiced, as he bought his Christmas toys for his children, that the t’gallant
yard had not gone with the sailor. No; on a yard in a storm I believed and
lived up to the maxim: “Hold fast to that which is good.” The yard was
good. Yet I was ambitious when a boy before the mast on the clipper which
brought me to California. I was quick to get into the rigging when there was
anything to do aloft. But once in the rigging I was of little utility.
The first time I went up at night to loose one of the royals, I thought I
should never stop climbing. The deck soon vanished in the darkness of a
very black tropical night, the mastheads were likewise lost in a Cimmerian
obscurity—whatever that is. At last I found the yard. I wasn’t quite sure
whether it was the right one or not. I didn’t know exactly what to do. I knew
I had to untie something somewhere. But where? Meantime the savage
Scotch second mate was bellowing, as it then seemed, a mile below me. I
knew the bellow was for me. I had to do something and I commenced
doing. I did know, or rather guessed, enough to cast off the lee and weather
gaskets, or lines which bind the sail when furled to the yard, and then I
made them up into a most slovenly knot. But the bunt-gasket (the line
binding the middle and most bulky portion of the sail), bothered me. I
couldn’t untie it. I picked away at it desperately, tore my nails and skinning
my knuckles. The bellowing from below continued as fiercely as ever,
which, though not intelligible as to words, was certainly exhorting me, and
me only, to vigilance. Then the watch got tired waiting for me. Thinking the
sail loosed, they began hoisting. They hoisted the yard to its proper place
and me with it. I clung on and went up higher. That, by the way, always
comes of holding fast to that which is good. Then a man’s head came
bobbing up out of the darkness. It was that of a good-natured Nantucket
boy, whose name of course was Coffin. He asked me the trouble. I went
into a lengthy explanation about the unmanageable knot. “Oh—the knot!”
said he. “Cut it!” and he cut it. I would never have cut it. In my then and
even present nautical ignorance I should have expected the mast or yard to
have fallen from cutting anything aloft. Only a few days previous I had seen
the Captain on the quarter-deck jumping up and down in his tracks with
rage because a common seamen had, by mistake, cut a mizzen brace, and
the second mate, as usual, had jumped up and down on the seaman when he
reached the deck. I feared to set a similar jumping process in operation.
Coming on deck after my lengthy and blundering sojourn loosing a royal, I
expected to be mauled to a pulp for my stupidity. But both watch and
bellowing mate had gone below and I heard no more of it.
CHAPTER V.

SAN FRANCISCO IN 1856.

The Wizard sailed through a great bank of fog one August morning and
all at once the headlands of the Golden Gate came in sight. It was the first
land we had seen for four months. We sailed into the harbor, anchored, and
the San Francisco of 1856 lay before us.
The ship was tied up to the wharf. All but the officers and “boys” left
her. She seemed deserted, almost dead. We missed the ocean life of the set
sails, the ship bowing to the waves and all the stir of the elements in the
open ocean.
The captain called me one day into the cabin, paid me my scanty wages
and told me he did not think I “was cut out for a sailor,” I was not handy
enough about decks.
Considering that for two months I had been crippled by a felon on the
middle finger of my right hand, which on healing had left that finger curved
inward, with no power to straighten it, I thought the charge of awkwardness
somewhat unjust.
However, I accepted the Captain’s opinion regarding my maritime
capacities, as well as the hint that I was a superfluity on board.
I left the Wizard—left her for sixteen years of varied life in California.
I had no plans, nor aims, nor purpose, save to exist from day to day and
take what the day might give me.
Let me say here never accept any person’s opinion of your qualifications
or capacities for any calling. If you feel that you are “cut out” for any
calling or that you desire to follow it, abide by that feeling, and trust to it. It
will carry you through in time.
I believe that thousands on thousands of lives have been blasted and
crippled through the discouragement thrown on them by relation, friend,
parent, or employer’s saying continually (or if not saying it verbally,
thinking it) “You are a dunce. You are stupid. You can’t do this or that. It’s
ridiculous for you to think of becoming this or that.”
The boy or girl goes off with this thought thrown on them by others. It
remains with them, becomes a part of them and chokes off aspiration and
effort.
Years afterward, I determined to find out for myself whether I was “cut
out for a sailor” or not. As a result I made myself master of a small craft in
all winds and weathers and proved to myself that if occasion required, I
could manage a bigger one.
San Francisco seemed to me then mostly fog in the morning, dust and
wind in the afternoon, and Vigilance Committee the remainder of the time.
San Francisco was then in the throes of the great “Vigilanteeism” of
1856. Companies of armed men were drilling in the streets at night. In the
city’s commercial centre stood “Fort Gunnybags”—the strong hold of the
Vigilantes—made, as its name implied, of sand-filled gunny sacks.
Carronades protruded from its port holes, sentinels paced the ramparts.
There was constant surging of men in and out of the building behind the
fort,—the headquarters and barracks of the Vigilantes. From its windows a
few days before our arrival they had hung Casey for the killing of James
King—one of the editors of the Bulletin. I saw two others hung there on the
sixth of August. Vigilanteeism was then the business and talk of the town.
The jail had just been captured from the “Law and Order” men, who were
not “orderly” at all, but who had captured the city’s entire governmental and
legal machinery and ran it to suit their own purposes.
The local Munchausens of that era were busy; one day the U. S. ship of
war, St. Mary’s, was to open fire on Fort Gunnybags; the next, Governor
Johnson, backed by twenty thousand stalwart men, was to fall upon the city
and crush out the insurrection.
The up-country counties were arming or thought of arming to put down
this “rebellion.” The “Rebellion” was conducted by the respectability and
solidity of San Francisco, which had for a few years been so busily engaged
in money making as to allow their city government to drift into rather
irresponsible hands; many of the streets were unbridged, many not lighted
at night. Cause—lack of money to bridge and light. The money in the hands
of the city officials had gone more for private pleasure than public good.
I speak of the streets being unbridged because at that time a large portion
of the streets were virtually bridges. One-fourth of the city at least, was
built over the water. You could row a boat far under the town, and for miles
in some directions. This amphibious part of the city “bilged” like a ship’s
hold, and white paint put on one day would be lead colored the next, from
the action on it of the gases let loose from the ooze at low tide.
There were frequent holes in these bridges into which men frequently
tumbled, and occasionally a team and wagon. They were large enough for
either, and their only use was to show what the city officials had not done
with the city’s money.
Then Commercial street between Leidesdorff and Battery was full of
Cheap John auction stores, with all their clamor and attendant crowds at
night. Then the old Railroad Restaurant was in its prime, and the St.
Nicholas, on Sansome, was the crack hotel. Then, one saw sand-hills at the
further end of Montgomery street. To go to Long Bridge was a weary, body-
exhausting tramp. The Mission was reached by omnibus. Rows of old hulks
were moored off Market street wharf, maritime relics of “ ’49.” That was
“Rotten Row.” One by one they fell victims to Hare. Hare purchased them,
set Chinamen to picking their bones, broke them up, put the shattered
timbers in one pile, the iron bolts in another, the copper in another, the
cordage in another, and so in a short all time that remained of these bluff-
bowed, old-fashioned ships and brigs, that had so often doubled the stormy
corner of Cape Horn or smoked their try-pots in the Arctic ocean was so
many ghastly heaps of marine débris.
I had seen the Niantic, now entombed just below Clay street, leave my
native seaport, bound for the South Pacific to cruise for whale, years ere the
bars and gulches of California were turned up by pick and shovel. The
Cadmus, the vessel which brought Lafayette over in 1824, was another of
our “blubber hunters,” and afterward made her last voyage with the rest to
San Francisco.
Manners and customs still retained much of the old “ ’49” flavor.
Women were still scarce. Every river boat brought a shoal of miners in gray
shirts from “up country.” “Steamer Day,” twice a month, was an event. A
great crowd assembled on the wharf to witness the departure of those
“going East” and a lively orange bombardment from wharf to boat and vice
versa was an inevitable feature of these occasions.
The Plaza was a bare, barren, unfenced spot. They fired salutes there on
Independence Day, and occasionally Chief Burke exhibited on its area
gangs of sneak thieves, tied two and two by their wrists to a rope—like a
string of onions.
There was a long low garret in my Commercial street lodgings. It was
filled with dust-covered sea-chests, trunks, valises, boxes, packages, and
bundles, many of which had been there unclaimed for years and whose
owners were quite forgotten. They were the belongings of lost and strayed
Long Islanders, ex-whaling captains, mates and others. For the “Market”
was the chief rendezvous. Every Long Islander coming from the “States”
made first for the “Market.” Storage then was very expensive. It would
soon “eat a trunk’s head off.” So on the score of old acquaintance all this
baggage accumulated in the Market loft and the owners wandered off to the
mines, to Oregon, to Arizona, to Nevada—to all parts of the great territory
lying east, north and south, both in and out of California, and many never
came back and some were never heard of more. This baggage had been
accumulating for years.
I used occasionally to go and wander about that garret alone. It was like
groping around your family vault. The shades of the forgotten dead came
there in the evening twilight and sat each one on his chest, his trunk, his
valise, his roll of blankets. In those dusty packages were some of the closest
ties, binding them to earth, Bibles, mother’s gifts, tiny baby shoes, bits of
blue ribbon, which years by-gone fluttered in the tresses of some Long
Island girl.
It was a sad, yet not a gloomy place. I could feel that the presence of
one, whose soul in sad memory met theirs, one who then and there recalled
familiar scenes, events and faces, one who again in memory lived over their
busy preparations for departure, their last adieux and their bright
anticipations of fortune, I could feel that even my presence in that lone,
seldom-visited garret, was for them a solace, a comfort. Imagination? Yes,
if you will. Even imagination, dreamy, unprofitable imagination, may be a
tangible and valuable something to those who dwell in a world of thought.
One night—or, rather, one morning—I came home very late—or, rather,
very early. The doors of the Long Island House were locked. I wanted rest.
One of the window-panes in front, and a large window-pane at that, was
broken out. All the belated Long Islanders stopping at the place, when
locked out at night, used to crawl through that window-pane. So, I crawled
through it. Now, the sentinel on the ramparts of Fort Gunnybags, having
nothing better to do, had been watching me, and putting me up as a
suspicious midnight loiterer. And so, as he looked, he saw me by degrees
lose my physical identity, and vanish into the front of that building; first,
head, then shoulders, then chest, then diaphragm, then legs, until naught but
a pair of boot-soles were for a moment upturned to his gaze, and they
vanished, and darkness reigned supreme. The sentinel deemed that the time
for action had come. I had just got into bed, congratulating myself on
having thus entered that house without disturbing the inmates, when there
came loud and peremptory rappings at the lower door. Luther and John, the
proprietors, put their heads out of the chamber windows. There was a squad
of armed Vigilantes on the sidewalk below; and, cried out one of them,
“There’s a man just entered your house!” Now I heard this, and said to
myself, “Thou art the man!” but it was so annoying to have to announce
myself as the cause of all this disturbance, that I concluded to wait and see
how things would turn out. John and Luther jumped from their beds, lit
each a candle and seized each a pistol; down-stairs they went and let the
Vigilantes in. All the Long Island captains, mates, coopers, cooks, and
stewards then resident in the house also turned out, lit each his candle,
seized each a pistol or a butcher-knife, of which there were plenty on the
meat-blocks below. John came rushing into my room where I lay,
pretending to be asleep. He shook me and exclaimed, “Get up! get up!
there’s a robber in the house secreted somewhere!” Then I arose, lit a
candle, seized a butcher-knife, and so all the Vigilantes with muskets, and
all the Long Island butchers, captains, mates, cooks, coopers, and stewards
went poking around, without any trousers on, and thrusting their candles
and knives and pistols into dark corners, and under beds and behind beef
barrels, after the robber. So did I; for the disturbance had now assumed such
immense proportions that I would not have revealed myself for a hundred
dollars. I never hunted for myself so long before, and I did wish they would
give up the search. I saw no use in it; and besides, the night air felt raw and
chill in our slim attire. They kept it up for two hours.
Fort Gunnybags was on Sacramento Street; I slept directly opposite
under the deserted baggage referred to. The block between us and the fort
was vacant. About every fourth night a report would be circulated through
that house that an attack on Fort Gunnybags would be made by the Law and
Order men. Now, the guns of Fort Gunnybags bore directly on us, and as
they were loaded with hard iron balls, and as these balls, notwithstanding
whatever human Law and Order impediments they might meet with while
crossing the vacant block in front, were ultimately certain to smash into our
house, as well as into whatever stray Long Island captains, mates, boat-
steerers, cooks, and coopers might be lying in their path, these reports
resulted in great uneasiness to us, and both watches used frequently to
remain up all night, playing seven-up and drinking rum and gum in Jo.
Holland’s saloon below.
I became tired at last of assisting in this hunt for myself. I gave myself
up. I said, “I am the man, I am the bogus burglar, I did it.” Then the crowd
put up their knives and pistols, blew out their candles, drew their tongues
and fired reproaches at me. I felt that I deserved them; I replied to none of
their taunts, conducted myself like a Christian, and went to bed weighted
down with their reproof and invective. The sentinel went back to his post
and possibly slept. So did I.
CHAPTER VI.

AS A SEA COOK.

I drifted around San Francisco for several months and finally shipped
as cook and steward of the schooner Henry, bound from San Francisco for a
whaling, sealing, abalone curing, and general “pick up” voyage along the
Lower Californian coast. My acceptance as cook was based on the
production of an Irish stew which I cooked for the captain and mate while
the Henry was “hove down” on the beach at North point and undergoing the
process of cleaning her bottom of barnacles. I can’t recollect at this lapse of
time where I learned to cook an Irish stew. I will add that it was all I could
cook—positively all, and with this astounding capital of culinary ignorance
I ventured down upon the great deep to do the maritime housework for
twenty men.
When we were fairly afloat and the Farallones were out of sight my
fearful incapacity for the duties of the position became apparent. Besides, I
was dreadfully seasick, and so remained for two weeks. Yet I cooked. It was
purgatory, not only for myself but all hands. There was a general howl of
execration forward and aft at my bread, my lobscouse, my tea, my coffee,
my beef, my beans, my cake, my pies. Why the captain continued me in the
position, why they didn’t throw me overboard, why I was not beaten to a
jelly for my continued culinary failures, is for me to this day one of the
great mysteries of my existence. We were away nearly ten months. I was
three months learning my trade. The sufferings of the crew during those
three months were fearful. They had to eat my failures or starve. Several
times it was intimated to me by the under officers that I had better resign
and go “for’ard” as one of the crew. I would not. I persevered at the
expense of many a pound of good flour. I conquered and returned a second-
class sea cook.
The Henry was a small vessel—the deck was a clutter of whaling gear.
Where my galley or sea-kitchen should have been, stood the try-works for
boiling blubber. They shoved me around anywhere. Sometimes I was
moved to the starboard side, sometimes to the larboard, sometimes when

You might also like