33% found this document useful (3 votes)
1K views

Full download Programming Principles and Practice Using C 3rd Edition Stroustrup pdf docx

Practice

Uploaded by

vitonyalch8k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
33% found this document useful (3 votes)
1K views

Full download Programming Principles and Practice Using C 3rd Edition Stroustrup pdf docx

Practice

Uploaded by

vitonyalch8k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Programming Principles and Practice Using C 3rd


Edition Stroustrup

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

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Programming: Principles and Practice Using C++ , Second


Edition Stroustrup

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

textboxfull.com

Programming Principles and Practice Using C Third Edition


Bjarne Stroustrup

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

textboxfull.com

A Tour of C 3rd Edition Stroustrup B.

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

textboxfull.com

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/

textboxfull.com
A Tour of C++ Stroustrup

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

textboxfull.com

A Tour of C++ Stroustrup

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

textboxfull.com

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/

textboxfull.com

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/

textboxfull.com

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/

textboxfull.com
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
[email protected] or (800) 382-3419.

For government sales inquiries, please contact


[email protected].
For questions about sales outside the U.S., please contact
[email protected].

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++
Random documents with unrelated
content Scribd suggests to you:
1810
CHAPTER IV
INTRODUCTION
The beginning of the year 1810 saw the army of Lord Wellington
withdrawn from Spain, and awaiting in Portugal the attack of the
French, which seemed the inevitable. It was destined to wait many
months before the blow fell. King Joseph and his advisers committed
the error of invading Andalusia, the subjugation of which, and the
siege of Cadiz, involved the employment of the larger portion of the
forces at their disposal. Before they could invade Portugal, it was
necessary for them to give time for reinforcements to arrive from
France. The Emperor, having concluded peace with Austria, was
now able to spare some of his legions for the complete conquest of
the Peninsula. But the time of waiting was long. Astorga in the north
did not fall till 22nd April; Ciudad Rodrigo was not taken till 9th July.
In July the opposing forces were brought into contact on the 24th
in the Combat of the Coa, in which, owing to the obstinacy of
General Crawfurd, the Light Division was severely handled by very
superior numbers and nearly cut off. Followed the advance of the
French army and the siege of Almeida, which was taken on 27th
August.
Meanwhile, during these weary months of waiting, the Portuguese
army was growing in numbers and steadily improving in efficiency
and discipline. The language used concerning it in the letters is full of
confidence, and offers a contrast to the rather despondent tone of
the references to it at the beginning of the previous year.
Major Warre, after a very busy time in August, seems to have
been attacked by his old malady and to have been sent to Lisbon.
He thus, much to his chagrin, missed Bussaco and the retreat to the
lines of Torres Vedras. Early in October he had recovered sufficiently
to rejoin the Marshal at his Headquarters within the lines. But the
hard life and exposure resulted in a very serious relapse, which
brought him to death’s door, and the Medical Board determined that
he must be sent home. He arrived at Falmouth, after a bad voyage
of ten days, early in November, and the last two letters of this year’s
series, from Falmouth and Honiton respectively, indicate a very
tedious journey and a precarious state of health.

LETTERS
Lisbon, Feb. 6, 1810.
My Dear Kind Mother,
I was made quite happy, on my arrival three days since at this
place, by receiving your affectionate letter of 29th Decr. and 1st
Jany. (I have also received yours of Dec. 12th)....
I own I think you very much more gloomy than necessary as to
public affairs, and do not agree with you as to Ministers, as I approve
much of many of their measures. Our misfortunes in Spain they
neither could foresee or prevent. Who could imagine the Spaniards
would betray those who went to their assistance? Cowards they are
not—that is the soldier. He is capable of being equal to any in the
world. But without Officers, or of course confidence, without
discipline and betrayed by their Government, what could they do?
Our last accounts, and their enemy being before Cadiz, was as
unexpected as an earthquake, and quite as unaccountable, as that
Spain has no army. They [the French] will find it very difficult to
conquer this country, and though things in Spain are certainly very
dispiriting, the game is not lost. Nothing, however, but a revolution
(horrid as the idea is to humanity) can save it, and that is already
begun, I suspect, and I hope the traitors will fall. I am quite of the
opinion that Public safety is the Supreme Law, and the cant of
humanity, when the country is to be saved, I consider as weak and
unmanly. They have paid dearly for a bigoted adherence to old
absurd forms and prejudices. I do not mean that a revolution and
popular Government will now save them. But I am sure that it is the
only thing that can. They are very enthusiastical and violent, and
they abhor the French, against whom their fury will be directed as
well as against their Government and traitors; and in this tumult
some great characters may start up.
As to Flushing, our expedition there was disastrous, but well
meant. Who could foresee that Austria would so soon make peace?
And the diversion, had it continued the war, would have been of
great consequence. Besides, as a soldier, I think we make too much
fuss about the loss of men where a great object is to be obtained.
Victorious or beaten we must lose men, but while we regret their loss
individually, we should not as a public one, in so glorious and just a
cause, that of our political existence as a nation.
I write to Tom some account of our tour, which was very pleasant,
though rapid. We travelled near 200 leagues in less than two
months. Nothing can exceed the beauty of part of the country we
went through, and we had only one day rain, and our inspection of
the progress of the discipline of the Portuguese troops was as
pleasant as our most sanguine wishes could expect.
I am very sorry you had not received the letters I wrote from this in
answer to that you wrote in company from Hendon, which I
answered, each individually. I wrote also to my father and Emily in
December, which letters I hope you have since received, and I only
did not write from Porto, as I intended, from really not having time
hardly to sleep or eat, what between duty and grand ceremonies and
rejoicings. Nothing can have been more honourable or flattering to
the Marshal than his reception in that City, and indeed in every place
we have been in throughout the country, and he deserves it for his
unremitted exertions, and Herculean labour. There exists not a more
honourable firm man or a more zealous Patriot. His failings are mere
foibles of a temper naturally warm and hasty, and great zeal to have
everything right, without much patience. Those who accuse him of
severity are either those who have felt it because they deserved it,
their friends, or people wilfully ignorant of the state in which he found
the army. And of how much he has foreborne, as to myself, I declare
I do not know one instance of severity, and [do know] numberless
ones of his mercy, and goodness of heart, where others would have
been less lenient. You see I insensibly fall into politics, or the shop,
so called, but one naturally writes about what one’s mind is
constantly occupied with, and as the subject is not uninteresting I
hope you will not be angry at my writing to a lady on such grave
matters as Politics and Tactics, or rather more properly speaking, on
public concerns.
I was three days at Arouca with dear Clara, who is a most amiable
sensible woman. Her manners and sense are really quite
astonishing for one so constantly secluded from the world. She was
quite well. We put the convent in a terrible fuss by the Marshal’s
arrival to breakfast there, on his way to Vizeu. It was very kind of him
to go to pay her a visit, and he was very much pleased with her.
I have got an order from the Nuncio to remove her where I please,
in case of danger, but it is not quite what I wanted, and I shall try to
get a more general one, and bring her to Lisbon, when necessary,
where my friends the Louriçals will be glad to receive her. The
Marchioness has just lost her sister the Duchess of Laffões, and has
the care and guardianship of the young Duchess and her sister,
nieces to the Prince, a dismal prospect for her, poor thing, in the
present state of public affairs, but notwithstanding she will not allow
me to place Clara anywhere else, and she cannot be with more
amiable charming people. Adieu, as I write to Tom and know that he
will see this letter, and you his, shall say no more, but beg you will
give kindest love to my dear father, with thanks for his letter, from
your sincerely affectionate Son,
Wm. Warre.

Lisbon, Feb. 17, 1810.


My Dear Father,
I avail myself of Frank Van Zeller’s going to England to thank you
for your very kind attention in sending me the books by John Croft,
and it was odd that I had, not half an hour before, finished the
translation into Portuguese of that on Light Infantry, when yours
arrived. It is, however, not less welcome, as coming from you, and
shall supply the place of the old one in our marches.
The great coat having brought a letter enclosed in it addressed to
the Marshal, it is a doubt whether it is for him or for me. It came
directed to me, and the letter enclosed is very equivocal. At all
events it does not fit me and does him, and therefore he shall keep
it, and if it is intended for me, he can send for one in its place that will
fit me. This sort of great coat, however, is of little use on horseback,
as it does not cover the knees. And as we can carry but little weight
on our horses and but very little baggage, a cloak lined with any
warm but light stuff is much better, as we oftener want a cloak to
sleep in than to keep out the rain, and I have latterly practised riding
with an oil skin cape over my great coat, and not minding the rain, so
long as I have anything dry to wrap myself up in, or sleep in, when
we arrive. Indeed my cloth coat gets so soon wet, is so heavy when
filled with water, and takes so many days drying, that I never carry it
with me, in order to save both myself and horse, and I find that we
get as used to being wet, and mind it as little, as we do many other
very disagreeable things.
Croft tells me you said something to him about a bear skin, which
you would send me, but I feel equally obliged by your affectionate
intention, and do not wish you to put yourself to the unnecessary
expense, as I have already a very good one, a former present from
Tom, and which I recovered after poor King’s death at Talavera.
I wrote so lately to Tom that I have very little more news to
communicate. Cadiz since the Duque d’Albuquerque got in with
6000 men, and the sailing of English and Portuguese Succours is, I
think, out of immediate danger, and indeed if the accounts we have
from Spain, and the non-arrival of reinforcements is true, as we
suppose, I cannot imagine that the French army can maintain itself in
Andalusia, and the movement appears to have been a very rash one
(though they succeeded in preventing the Cortes, a great object) and
one which they may bitterly repent. It is, however, impossible to say.
They are very clever fellows, and have too much experience to make
any very great faults, and it is impossible for us to know the secret
causes or encouragement which induced them to take such a step.
Even the people who are about a General Officer Commanding
know very little of the motives which weigh in his mind and make him
act, and but very few indeed are capable, at the moment, of judging
of its expediency or propriety, even long after, when results are
known, and time has developed many of the circumstances, and the
real situation in which they were placed. We cannot be too cautious
in blaming or approving the conduct of one entrusted with such a
command. For we can never fully know what passes in his mind
(unless greatly in his confidence), or the numberless combinations
he must regard. We can only form to ourselves an opinion of how far,
and with what propriety apparent, he has deviated from, or adhered
to, the certain fixed principles of war, which are subject to as much
modification as the variety of the ground to which they must be
adapted.
They have also advanced a Corps of 6 to 8000 men upon
Badajos, in which Romana is with 6000 men, and a lesser towards
Olivença, another upon Ciudad Rodrigo, which, I hear, is not strong,
but am ignorant of their numbers, or of what garrison is in the place.
These Corps threaten us direct, but I am of the opinion that it is
merely a demonstration in order to deceive and restrain the British
and Portuguese army, by making them jealous of their approach,
and collecting the forces for fear of an immediate attack, as I have a
letter from a friend of mine in Spain who denies that any
reinforcements have arrived, and says he had just spoken with a
Spanish Courier, who passed Bayonne on the 19th ulmo., and
reports that no reinforcements had arrived there at that period, or
were any immediately expected, and that the state of the Public mind
in France was far from favourable to Buonaparte. Of this you may
believe as much as you please, combining it with what reports you
have in England. Spaniards more frequently report what they wish
than what is true, as we all well know to our cost.
General Hill’s Corps, British and Portuguese, have been marched
towards Elvas to cover our sick and wounded at that place. The
Portuguese troops are in very high spirits and seem anxious to meet
the enemy. They are in a very improved state of discipline, and
promise well. It would be unfair to doubt them with these qualities.
Poor fellows, they fight for everything that is dear to them. I never
saw a Regt. embark in better style or higher spirits than 20th
Portuguese Regt. did for Cadiz a few days ago. They embarked
1400 strong, and lost only 6 deserted, which does them and their
country great honour. Several men came and enlisted at the moment
the Regt. was embarking, and one fine fellow I enlisted myself as the
Regt. marched off. The son of the Viscondessa de Misquetella also
enlisted at that moment. Everything proclaims an active spring, and I
am very glad of it. The French will, I dare hope, find themselves
mistaken in the Portuguese troops, and though I am not sanguine as
to the final result, unless Spain does more than she has done yet, I
am sure the Conquest will cost them very dear.
Pray thank ... for their affecte. letters by John Croft, whom I was
much astonished to see in Lisbon, and also for the bonnets for
Lumiaces which are much approved. I have also received your
letters by Mr Knox and Stanhope and that from my Uncle Wm., and
will, of course, shew them every kindness in my power, though I
regret the state of the Public mind, which is a bar to much society,
and my mixing very little in any society whatever, will prevent my
shewing them as much of it as I could wish. I have offered them my
horses, and will endeavour to ask them here as often as I can.
Our stay is very doubtful, and of course very much depends upon
the movements of the enemy, nor have I yet an idea as to where our
Hd. Qrs. are to be. Your most truly affectionate,
Wm. Warre.

Lisbon, March 10, 1810.


My Dearest Mother,
We have been unexpectedly delayed in Lisbon some days owing
to the dreadful storms we have experienced for the last 8 days,
during which it has rained in torrents, and blown almost a hurricane.
Great damage has been done in the River, and for several days and
nights we have heard nothing but signals and guns of distress in the
River even above Lisbon, though I have not yet heard of many lives
being lost. I comforted myself with the idea that it will fill our Rivers
for us, and render all the fords impassable. We are likely to remain a
day or two longer in Lisbon and then go to Coimbra, which for the
present will be the Marshal’s Hd. Qrs. The enemy has latterly been
very quiet, and we have had very quiet winter quarters, a luxury very
rare in the present system of warfare. This, however, cannot now last
long, and I hope ere long some movement will be made on one side
or the other.
The supineness of the Spaniards is truly distressing. Poor devils,
they have been most shamefully betrayed by their Government, and
public confidence appears in that country quite lost. It is really
mortifying, for they are an enthusiastic and spirited people, and have
shown on some occasions that they are not deficient in individual
courage. I wish they were in half the state of discipline and
organisation of the Portuguese, and the French would not then find it
an easy task to maintain themselves in that country with their
present force; and nothing but the French being perfectly well
informed of the real state of that unfortunate nation could have
induced them to make the rash movements which they have, for, in
any other point of view, they appear much allied to absolute folly.
With regard to this country much is to be said, but my motto is “Nil
Desperandum.” Our Commanders are very clever, and of course
know better than anybody how they can defend the country, and
every Officer who feels like a soldier should not form, or at least
communicate, theories of his own, but make up his mind to share
their fate, be it what it may.
To put my mind at rest I have obtained an order to remove dear
Clara to the Convent of the Esperança at this place. This from the
Nuncio who has also written a very kind letter to the Bishop of
Lamego to facilitate the business. These I gave to the Patriarch a
fortnight ago, and he told me to set my mind at rest, and that he
would arrange the whole business for me in the best manner. She
will be within reach of the Marshal’s protection in case I should be at
a distance in time of need, should it come to that extremity, and my
friend the Marchioness of Louriçal has promised to treat her as if she
belonged to her family, and it is to her exertions and friendly
interference that I am indebted for having her admitted into this
convent, which is the best, and the Lady Abbess a friend of hers.
Should they be forced to embark, of which I see however no present
probability, she will take her with her, and even should that not be
easy, I feel confident I can depend upon the Marshal’s friendship and
protection, therefore pray tell my dear Father, that he may set his
mind quite at rest, and she is truly deserving of all our love and
affection.
My stay in Lisbon this time has been anything but amusing. There
has been very little gaiety, and my time fully employed with my friend
John Campbell in compiling a set of regulations for the Cavalry, the
last I hope I shall be bothered with, for I know from experience that
we may write out our finger ends, and nobody thank one, even if we
were to put the regulations into Hexameter and Pentameter verse!
Pray give my kindest love to my dear Father, etc., and remember
me most kindly to all my friends. Ever, my dearest kind Mother, your
truly affectionate Son,
Wm. Warre.
I have not heard from any of you for some time.

Coimbra, March 21st, 1810.


My Dear Father,
We arrived here yesterday from Lisbon after a rather tedious and
rainy journey, and have for the present established our Hd. Qrs.
here, but for how long it is impossible to say, or where we shall go
when we do move. Both must depend entirely upon the enemy, who
have given us a much longer period of tranquillity than I expected.
The bubble, however, must soon burst, and I expect to hear daily of
their making some movement, for we have very good reason to
suppose they are much distressed by the want of provisions, a want
they are not likely to mend by entering this country, in itself
considerably exhausted, and where every means will be taken to
place what is remaining out of their reach, or destroy it, in case we
should be forced to retreat.
I am anxious that the campaign should begin; and to be able to
judge of what our Portuguese will in reality do. I confess I have very
great hopes of them. Their discipline is most wonderfully improved,
perhaps fully as good as necessary for active service, and only
wants confirming. I fear their relaxing, when they get out of the
immediate control of British Officers, before the enemy, and the class
of their own Officers, though very much improved and mostly young
men, have scarce experience and firmness enough to control them
as we could wish. Their pay, which has in some cases been more
than doubled, gives them the means now of living like gentlemen
and with respectability. In some cases it is better than ours in
proportion, and since the service becomes an object, they will, we
must hope, exert themselves, that they may not be deprived of it,
which they certainly will without remorse, if they misbehave at all.
Our cavalry is also getting into a very respectable state, and now
very tolerably mounted. I saw the 4th commanded by Lt.-Col.
Campbell, Augustus’ brother, manœuvre at Lisbon at a gallop
extremely well, certainly beyond anything Portuguese Officers had
any idea of, and they are certainly equalled by the 1st Brigade, and
Madden’s the 2nd, which is mounted on mares, and I doubt will be
able to bear the work equal to the other. It is an experiment, and my
private opinion is that it will not succeed. Two Brigades of very fine
infantry, the 1st cavalry, and 3rd Brigade of Artillery, are with Genl.
Hill on the Frontier of Alemtejo, and I believe several other Brigades
will be attached to the British Army in the Beira, and I think it most
probable that some English Regts., as a reserve, will be attached to
Marshal Beresford’s Corps d’Armée. But where we are to go, or what
to do, I am perfectly ignorant.
I shall be much obliged to you to send me out a map of Spain and
Portugal, published by Fadan, and compiled by Nantiat. It appears to
be the best extant, and I am in want of a good one, so much so that
you will much oblige me by sending it out by the very first
opportunity, and Col. D’Urban, our Quarter-master General, begs me
to procure him one also. They must be pasted on canvas and in
strong cases. I have just been calling on General Payne, who asked
very kindly after you.
The Spaniards have attacked the French at Caçeres and at
Valverde and beat them, killing at each a General, one of Division.
Though these affairs are of no great consequence in themselves,
they may revive the dormant enthusiasm and patriotism of the
Spaniards, but I confess I have very slender expectation of it. At
Valverde it was done in a very slovenly manner, for they completely
surprised the French, and the French General was in bed, but they
amused themselves murdering a few unfortunate devils whom they
first met, and let him get away with some Dragoons. At Caçeres had
their Cavalry behaved as well as their Infantry they would have taken
or destroyed all the French, who prepared to receive them, but were
completely beaten and followed for about a league.
Believe me ever most truely your affectionate Son,
Wm. Warre.
There has been a little trifling outpost work beyond Almeida on the
Agueda. We had one Hussar killed. But this is of no consequence
and leads to nothing.
March 23, 1810, W. W.

Coimbra, March 30, 1810.


My Dearest Brother,
The last two days have been fertile in happiness, as in them I have
received all the letters from my dear family. Yours of the 5th is this
instant arrived. The breeches, etc., by Col. Brown I have received
and not before they were wanted. I am much amused by the cause,
though sorry for the fright you are all in. We cannot ourselves see
any reason for this dread, and are spending our time pleasantly
enough in peace and quietness, so much so that we are all sighing
for a more active scene. Now I confess I do not think this far distant,
but that the result is to be so disastrous to us I do not believe. I
cannot think where the people in England get their information,
certainly not from Portugal. It must be from “Bony,” or it would not be
given such disastrous colours, alarming our beloved families without
any reason. You know my opinion of the ultimate result of the
contest, unless something unexpected turns up in the north, or in
Spain. But we are only at the beginning, and there is a great deal to
be done before we are forced to embark yet, if it should ever come to
that.
What most annoys me is our British House of Commons,
particularly the late Debates. Bonaparte can never want spies or
intelligence, while that House tells our exact force and dispositions. I
love the liberty which distinguishes their discussions, but abhor the
folly which makes each side sacrifice the interests of their country to
their villainous party interest. They will tell the force, station,
expence, of your armies; they will foment discontent and distrust,
treat your allies with disrespect, and (with regard to what they said of
Portugal) with falsehood, to vex Ministers and get themselves in, and
vice versâ, for I think one as bad as the other.
I am much delighted with your account of my Mother, whom pray
tell that she need not be in the least alarmed about her tall son, who
will take great care of himself for her sake, and that at present he
cannot see any danger except of growing too fat, from having little to
do and good living, and I will write to her by the next Packet.
I cannot tell you what will be done with the Portuguese troops, who
are really in very high state of drill and appearance, and, I have no
doubt myself, will do their duty. For I do not know very well myself; at
all events, my private opinion is that it would be folly to leave them
for the French, but these are after considerations, and no doubt
when it comes to that push, proper measures will be taken....
Hd. Qrs., Mango Alde, May 3rd, 1810.
My Dearest Father,
It is indeed difficult to express to you the pleasure with which I
read your very affectionate kind letter of the 8th of April. The
approbation you express of my conduct (founded on the flattering
accounts of my friends always willing to gratify a parent’s feelings) is
the greatest reward I can ever wish for.
I avail myself of a courier, which the Marshal is sending to Lisbon,
to write these few lines and to inform you that soon after my return
from Porto to Coimbra, the Marshal went over to Vizeu, but I
remained behind to rest my horses. But on the 26th, owing to some
movement of the mounseers upon Ciudad Rodrigo, our army
received orders to march immediately, which they did on the 27th, on
which day I arrived at Vizeu, and found, to my great satisfaction, that
the Marshal, who, I heard, was ill, was nearly recovered, and only
suffered from a very severe cold. We remained there till the 1st,
giving time to our troops to arrive, and then moved the Hd. Quarters
to this place, and to-day, the 3rd May, we move on the Fornos
d’Algodres, where we expect to remain a few days. This, however,
must depend on the movements of the enemy, or Lord Wellington’s
plans, and I am as ignorant of the intentions of the one as of the
other. I conjecture that if they persist in the siege of Ciudad Rodrigo,
an action is inevitable. Our Army is in the highest spirits—and we all
wish it. Notwithstanding the very unfavourable weather we have had,
as it has rained incessantly during the whole of their march, the
Portuguese troops are in the highest spirits, and seem anxious to
prove the good effects of their discipline and reorganisation.
English Hd. Qrs. are at Celorico and the Army in that
neighbourhood advanced as far as Gallegos. The French are about
Tamames, St Espiritu, and advances before Cd. Rodrigo.
Ballesteros, in the Sierra Morena, has been beaten, but not routed,
“que milagre.”[19] Genl. Hill made a forward movement at the end of
last month in order to disengage O’Donnel the Spanish General, who
was at Albuquerque. But on the French retreating he returned to
Portalegre. Their Germans and Italians desert in great numbers. I
have seen several parties of them who are remarkably fine men, and
very well clothed, but they complain of never being paid, and that the
French treat them like canaille. Nor have they enough to eat. Many
more would desert, but they are afraid of the Spanish and
Portuguese peasantry, who murder every thing that wears a French
uniform. Yesterday 23 went through from Braganza. They were
Prussians taken at Jena and forced to serve. They told me they had
rather serve us than the enemies of their country. I never saw finer
men.
I now come, my dear Father, to a part that interests us more
nearly, and I am very sorry to tell you that dear Clara has
(notwithstanding the trouble I was at in preparing everything for her
removal) refused to quit the convent. I have written to her in the
strongest manner, and urged the propriety of this temporary
inconvenience in the most forcible language, telling her how
impossible it will be for me, should real danger occur, to break my
trust by warning her even distantly, my principal reason for wishing to
remove her, but all in vain. The nuns do all they can to prevent her,
and every intrigue is used. It is their interest they fancy that she
should remain, and you know the power those silly women have over
her mind. She is, I fear, unwell with the agitation, and when Frè
Bernardo went to bring her away, she pleaded illness not to see him,
and he came away as he went. I am much vexed and annoyed at
her resistance, but can do no more. It places me in a most
unpleasant situation. I, however, enclose hers and the Abbess’
answers to my letters, and from them you will be able to judge of
what I have had to fight against. I really believe, poor thing, that she
is ill, and dare not press her farther, and trust only that neither herself
or any of her friends may have reason to repent her folly.
I am very much obliged to you for the maps of the Tagus, Spain,
and Portugal. The latter I much wanted.
I am not surprised at Wilson’s not mentioning the Marshal, who
has no reason to be pleased with him. Nobody will deny him courage
and talents as a Partizan, but to those who know facts, the attempt
at thanks in the House are more adapted to make him appear
ridiculous, than to do him honour. He can never want a trumpeter
while he lives, and no man better knows the art de se faire valoir. He
must really be a clever fellow, to have, with 700 undisciplined
Portuguese, checked 30,000 French, terrified them much, and at the
same time covered upper and lower Beira, Almeida, Ciudad Rodrigo,
and ensured the retreat of English detachments, which the enemy
never attempted to impede. Many other of his deeds, mentioned by
the Hon. member, we never heard of. He is a very good fellow as a
companion, and a very able light troop Officer, and if he would not
attempt to be more than he really is, would be more respected. His
conduct to the Marshal I can never approve, and he himself must
feel lowered in his own estimation by it.
I have been obliged to leave a horse I gave 80 guineas for lame at
Coimbra, and am reduced to two. On my return to Lisbon, however,
whenever that period arrives I shall be able to buy another without
drawing on England at all.
Pray give my kindest love to dear Mother, etc. Adieu my dearest
Father. Ever your most obliged and most sincerely affectionate son,
Wm. Warre.
The Marshal desires to be most kindly remembered. H. Brown,
who, poor fellow, has been very unwell at Lisbon, desires me in all
his letters to say as much.
P.S.—Ciudad Rodrigo is a wretched place, considered as a
fortified town, perhaps à l’abri of a coup de main, but I think would
not stand a regular siege for a week. Our neighbourhood may
encourage the inhabitants however, while it checks the assailants,
and they may do wonders as many other Spanish towns have. I fear
Astorga has fallen, though I do not know it for certain. We have lost a
few men at Cadiz and Col. le Febre our Chief Engineer, while
evacuating an advanced work, which the enemy had nearly
demolished with their artillery.

[19] What wonder!


Extract from Letter to Sister.
Fornos d’Algodres, May 9, 1810.
We have had our Hd. Qrs. at this place for some days, nor do I for
the present see much chance of our moving. It is a miserable little
place, and in the whole of this house there are but half a dozen
panes of glass in one window, and we are three in a small room,
through the ceiling of which we receive light enough to save us the
trouble of opening the window. It is, however, better than many we
have had, and shall have, and therefore we are quite contented.
Besides the house is full of Senhoras, pretty enough, if they would
wash their faces and comb their hair, but you know Fidalgas and
Fidalgos d’Albea have a right ab origine to be as filthy as they
please, so long as they have finery and tinsel. I am much amused
with the airs and affectation of these grands du village, who however,
we must confess, are very kind and civil, and, to their no small and
our very great annoyance, dine and breakfast with us à l’Anglaise.
We went last week over to Celorico the English Hd. Quarters, and
staid two days, on one of which we went over to Guarda and
reviewed two Portuguese Regts. under torrents of rain, such as I
never before recollect. Indeed, for the last three months this weather
has been constant, as in that time we have not had three fine days. It
looks better to-day, and for the sake of the troops I sincerely hope it
will settle. I was much flattered by Lord Wellington’s reception and
kindness to me, and respect him too much to be indifferent to his
good opinion. He appears confident and in spirits, and all his army
are in the finest order, as are indeed comparatively our Portuguese,
who have all shown great spirit in this hasty advance, and the
greatest wish to meet the enemy.
I forgot to mention to you our family consists of six or seven grown
up young ladies, all of whom firmly believe that your letter was from
a love, as I walked into my room to read it, and seemed much
pleased at the receipt of it. They rally me very much about a Minha
Carida, and I do not deny I love you very much! I have a Valet de
Chambre, a Portuguese, one of the finest gentlemen I know, but not
a bad servant, if he was less affected, and less fond of his ease. He
is a much greater man than I am. I have also a man from the 23rd, a
very decent quiet groom and very fond of his horses.
With kindest love, believe me, etc. etc. etc.,
Wm. Warre.

Hd. Quarters, Fornos D’Algodres, 15 May 1810.


My Dear Father,
I wrote to you a few posts ago from Mangoalde, informing you of
the very bad success I had in my attempt to remove dear Clara to
Lisbon. After having everything arranged I am sorry to say that the
agitation and distress it occasioned her was the cause of a slight
fever. Poor thing! such is the effect of superstition and popish
influence, and I have been much alarmed about her. However she is
much better, indeed, I hope, by this time quite recovered. My
situation with regard to her is very unpleasant. I dread urging the
business or committing myself by writing very strongly to her; and
still, in prudence, I cannot be happy while she remains there. There
is certainly no immediate cause of dread of the enemy, but a battle
may decide much, and I know too much of war ever to wish any
person that is dear to me to be even distantly exposed to its
chances. I am therefore anxiously waiting to know your wishes about
how I am to proceed. I much fear her health would suffer materially
by insisting on her removal, and on the other hand, when there shall
be any immediate cause of alarm, how can I risk alarming a whole
Province by informing her of it. How difficult it is sometimes to
reconcile private feelings to public duty! The latter, however, is
imperious.
I have been much flattered lately by Ld. Wellington’s reception of
me, and lately remained two days at his Hd. Qrs. at Celorico 2
leagues from here. He has applied to me to procure him one Hghd.
of very fine old Port. He does not care about the price, and wishes
me to get you to take care of it for him in London. At Oporto it is
impossible to get any old wine, and I therefore told him I would write
to you, and beg your assistance. It is, I suppose, for some very
particular purpose, and I shall therefore be glad to know how far you
can assist me. It may be bem empregado,[20] and may lead to an
acquaintance on our return to England between you and a man of
first-rate abilities. He says he thinks you ought to get one for him in
return for his having taken away my snuff-box, though I am sorry to
confess he has not made me leave off that vile custom, though he
made me promise not to carry a box, to the no small annoyance of
my friends on whom I must trust for my supply.
I have received the price of the Pipe of wine shipped by you for Sir
David Dundas, and delay sending it, in the first place, till I can get a
bill, and in the next, that having received it in six Milfour pieces, I can
scarce bring myself to part with them, as they are very scarce, and
Dollars most inconvenient to carry about. I will write to Mr John Bell,
who pays us, to buy a bill for the number of Dollars, and remit it to
you, or will buy one myself, if I can, before next packet.
Our accounts from the French army are that they are very sickly;
in Salamanca are about 2000 sick, who die 30 or 40 of a day. Their
troops are also much dissatisfied, particularly the Germans and
Italians, who compose the chief part, and those desert very fast, and
would much more, if they were not exposed to be murdered by the
Peasantry, whether deserters or prisoners. It is really horrible, and
defeats the exertions which are making to entice them to fly from
their oppressors, and they are willing enough but for these
difficulties. Some have come over horses and all. I never saw
handsomer or finer looking men. They all agree in complaining that
they are never paid, and but indifferently fed, and that they are
constantly harassed and marched about. From the accounts we
have, the French force immediately before us may be of 30,000
men, more or less, and certainly sickly. The constant rains which
have continued for the last 3 months have been much against them.
It is pretty sure now that they intend to attack Ciudad Rodrigo, which
is a place of no strength, and their heavy artillery is on its march to
that place, which has been summoned in a very imperative manner.
Masséna is reported to have arrived to take the command of the
whole of this army. I am most anxious to know what steps Lord
Wellington will take to prevent the reduction of Ciudad Rodrigo. It is
of, I consider, the greatest consequence that it should be protected,
if possible. It is a sort of outer door to our house, and, in the
possession of the enemy, would enable him to establish his
Magazines, Hospitals, etc., nearer to our frontier than we could wish.
Ld. Wellington and Marshal Beresford know best however, and I
shall feel confident of the propriety of whatever they do. I shall
rejoice very much at quitting this miserable village, where we are
very badly off.
Our troops as well as the English are well, and in high spirits,
though in my opinion these cantonments in small detached villages
are greatly detrimental to their discipline, of which, however forward
and astonishing, they cannot have acquired yet that habit which will
admit of any relaxation. I am, however, confident that where they are
commanded by British Officers they will behave well, and that, at the
end of the Campaign, they will have acquired a character as Troops.
It will indeed be heart-breaking to poor Marshal Beresford if they do
not. His exertions have been Herculean and indefatigable, and their
good effects felt in every branch of the Legislature, and has even
now done enough to establish his character as a very superior,
strong-minded, clever Officer, and should his labours be crowned
with the success they deserve, he will become one of the most
eminent men in England, and have deserved more of this country
than they can ever repay. I cannot sufficiently admire the firmness
and understanding with which he has overcome difficulties, which
would have disheartened and overturned the plans of most, even
very superior men. He is just the man for this particular service.
Waters passed through this place yesterday with General Stewart.
He is quite well, and gave me great pleasure by the accounts he
gave me of all the dear family. By him I received the chart of the
Tagus, for which I am very much obliged to you, as also for the
drawers, which I fear are somewhat too small for me, but must do.
I feel considerably distressed at the accounts from England. I
always felt that we had nothing to fear against our foreign enemies
whilst united amongst ourselves, and have long observed the
struggles of a particular and very infamous set of men, to sap the
public confidence in their Government and Constitution, for it is at
that they now strike direct, and neither the respectability of the King,
nor the critical situation of the country, can prevent these fellows
from endeavouring to create confusion and a revolution, in which the
mob are to have the lead, for by that alone can such designing
unprincipled miscreants be countenanced or exalted to any power. I
consider the question as no longer one of opposition against
Ministers; that I should not mind. It is in the very nature of our
constitution. But the question is now whether the country is in such a
distressed situation from unhappy political circumstances—whether
the want of unanimity of Ministers, and the state of mind of the dregs
of Society, are in such a state, that Sir F. B.[21] and his gang can
expect to be able to overturn the constitution, and raise themselves
upon the wreck of their country. I have no patience that such fellows
have so long gone on without punishment, and the seeds of civil
discord once sown, there is no knowing where it may end. There are
never wanting factious, needy men to foment it, who, having nothing
to lose but their lives, would sacrifice their country to gain something
in the appearance of power. Respectability is out of the question.
Adieu. Pray now and then send me the general opinions of the
day. To us at this distance they are highly interesting. Pray give my
most affecte. love to my dear mother, etc., etc., etc., and believe me,
Ever my dear Father Your most affectionate son,
W. W.
P.S.—
Fornos D’Algodres, May 23rd, 1810.
Masséna is just arrived to take the command of the army of
Portugal now between Ciudad Rodrigo and Salamanca, which
consists of Ney, Soult, and Mortier’s Divisions. He is one of B.’s best
generals. I dare say he will shortly attempt something, but we are too
well prepared to fear much his first attack, but how far we shall
ultimately be able to resist numbers upon numbers, unless Spain
assists us, is another question.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like