6480Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design 1st Edition Dmitri Nesteruk instant download
6480Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design 1st Edition Dmitri Nesteruk instant download
https://textbookfull.com/product/design-patterns-in-modern-c-
reusable-approaches-for-object-oriented-software-design-1st-
edition-dmitri-nesteruk/
https://textbookfull.com/product/design-patterns-in-net-
core-3-reusable-approaches-in-c-and-f-for-object-oriented-
software-design-2nd-edition-dmitri-nesteruk/
https://textbookfull.com/product/head-first-design-patterns-
building-extensible-and-maintainable-object-oriented-
software-2nd-edition-eric-freeman/
https://textbookfull.com/product/mastering-php-design-patterns-
develop-robust-and-reusable-code-using-a-multitude-of-design-
patterns-for-php-7-ali/
https://textbookfull.com/product/primary-mathematics-
textbook-2b-jennifer-hoerst/
Systems Analysis and Design An Object Oriented Approach
with UML Dennis
https://textbookfull.com/product/systems-analysis-and-design-an-
object-oriented-approach-with-uml-dennis/
https://textbookfull.com/product/programming-in-c-object-
oriented-features-1st-edition-laxmisha-rai/
https://textbookfull.com/product/practical-object-oriented-
design-an-agile-primer-using-ruby-second-edition-metz/
https://textbookfull.com/product/making-embedded-systems-design-
patterns-for-great-software-2nd-edition-elecia-white/
https://textbookfull.com/product/making-embedded-systems-design-
patterns-for-great-software-2nd-edition-elecia-white-2/
Design Patterns
in Modern C++
Reusable Approaches for
Object-Oriented Software Design
—
Dmitri Nesteruk
Design Patterns in
Modern C++
Reusable Approaches for
Object-Oriented Software
Design
Dmitri Nesteruk
Design Patterns in Modern C++: Reusable Approaches for Object-Oriented
Software Design
Dmitri Nesteruk
St. Petersburg, Russia
Chapter 1: Introduction������������������������������������������������������������������������1
Preliminaries���������������������������������������������������������������������������������������������������������2
Who This Book Is For���������������������������������������������������������������������������������������2
On Code Examples�������������������������������������������������������������������������������������������3
On Developer Tools������������������������������������������������������������������������������������������4
Piracy���������������������������������������������������������������������������������������������������������������5
Important Concepts�����������������������������������������������������������������������������������������������5
Curiously Recurring Template Pattern�������������������������������������������������������������5
Mixin Inheritance���������������������������������������������������������������������������������������������6
Properties��������������������������������������������������������������������������������������������������������7
The SOLID Design Principles���������������������������������������������������������������������������������8
Single Responsibility Principle������������������������������������������������������������������������8
Open-Closed Principle�����������������������������������������������������������������������������������11
Liskov Substitution Principle�������������������������������������������������������������������������18
Interface Segregation Principle���������������������������������������������������������������������21
Dependency Inversion Principle��������������������������������������������������������������������24
Time for Patterns!������������������������������������������������������������������������������������������28
iii
Table of Contents
Chapter 3: Factories���������������������������������������������������������������������������49
Scenario��������������������������������������������������������������������������������������������������������������49
Factory Method���������������������������������������������������������������������������������������������������51
Factory����������������������������������������������������������������������������������������������������������������52
Inner Factory�������������������������������������������������������������������������������������������������������54
Abstract Factory��������������������������������������������������������������������������������������������������56
Functional Factory����������������������������������������������������������������������������������������������59
Summary������������������������������������������������������������������������������������������������������������60
Chapter 4: Prototype���������������������������������������������������������������������������63
Object Constrution����������������������������������������������������������������������������������������������63
Ordinary Duplication�������������������������������������������������������������������������������������������64
Duplication via Copy Construction����������������������������������������������������������������������65
Serialization��������������������������������������������������������������������������������������������������������68
Prototype Factory������������������������������������������������������������������������������������������������72
Summary������������������������������������������������������������������������������������������������������������74
iv
Table of Contents
Chapter 5: Singleton���������������������������������������������������������������������������75
Singleton as Global Object����������������������������������������������������������������������������������75
Classic Implementation���������������������������������������������������������������������������������������77
Thread Safety������������������������������������������������������������������������������������������������79
The Trouble with Singleton���������������������������������������������������������������������������������80
Singletons and Inversion of Control��������������������������������������������������������������������84
Monostate�����������������������������������������������������������������������������������������������������������85
Summary������������������������������������������������������������������������������������������������������������86
Chapter 7: Bridge��������������������������������������������������������������������������������99
The Pimpl Idiom��������������������������������������������������������������������������������������������������99
Bridge���������������������������������������������������������������������������������������������������������������102
Summary����������������������������������������������������������������������������������������������������������105
Chapter 8: Composite�����������������������������������������������������������������������107
Array Backed Properties�����������������������������������������������������������������������������������108
Grouping Graphic Objects���������������������������������������������������������������������������������111
Neural Networks�����������������������������������������������������������������������������������������������114
Summary����������������������������������������������������������������������������������������������������������118
v
Table of Contents
Chapter 9: Decorator������������������������������������������������������������������������119
Scenario������������������������������������������������������������������������������������������������������������119
Dynamic Decorator�������������������������������������������������������������������������������������������121
Static Decorator������������������������������������������������������������������������������������������������124
Functional Decorator�����������������������������������������������������������������������������������������127
Summary����������������������������������������������������������������������������������������������������������131
vi
Table of Contents
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
Index�������������������������������������������������������������������������������������������������309
x
About the Author
Dmitri Nesteruk is a quantitative analyst,
developer, course and book author, and an
occasional conference speaker. His professional
interests lie in software development and
integration practices in the areas of computation,
quantitative finance, and algorithmic trading.
His technological interests include C# and
C++ programming as well high-performance
computing using technologies such as CUDA
and FPGAs. He has been a C# MVP since 2009.
xi
About the Technical Reviewer
Massimo Nardone has more than 24 years
of experiences in Security, Web/Mobile
development, Cloud, and IT Architecture. His
true IT passions are Security and Android.
He has been programming and teaching
how to program with Android, Perl, PHP, Java,
VB, Python, C/C++, and MySQL for more than
20 years.
He holds a Master of Science degree in
Computing Science from the University of
Salerno, Italy.
He has worked as a Project Manager, Software Engineer, Research
Engineer, Chief Security Architect, Information Security Manager, PCI/SCADA
Auditor, and Senior Lead IT Security/Cloud/SCADA Architect for many years.
Technical skills include: Security, Android, Cloud, Java, MySQL,
Drupal, Cobol, Perl, Web and Mobile development, MongoDB, D3,
Joomla, Couchbase, C/C++, WebGL, Python, Pro Rails, Django CMS, Jekyll,
Scratch, etc.
He worked as visiting lecturer and supervisor for exercises at the
Networking Laboratory of the Helsinki University of Technology (Aalto
University). He holds four international patents (PKI, SIP, SAML, and Proxy
areas).
He currently works as Chief Information Security Office for Cargotec
Oyj and he is a member of ISACA Finland Chapter Board.
Massimo has reviewed more than 45 IT books for different publishers,
and coauthored Pro JPA 2 in Java EE 8 (Apress, 2018) and Pro Android
Games (Apress, 2015).
xiii
CHAPTER 1
Introduction
The topic of Design Patterns sounds dry, academically constipated and,
in all honesty, done to death in almost every programming language
imaginable—including programming languages such as JavaScript that
aren’t even properly OOP! So why another book on it?
I guess the main reason this book exists is that C++ is great again. After
a long period of stagnation, it’s now evolving, growing, and despite the
fact that it has to contend with backwards C compatibility, good things are
happening, albeit not at the pace we’d all like. (I’m looking at modules,
among other things.)
Now, on to Design Patterns—we shouldn’t forget that the original
Design Patterns book1 was published with examples in C++ and Smalltalk.
Since then, plenty of programming languages have incorporated
design patterns directly into the language: for example, C# directly
incorporated the Observer pattern with its built-in support for events
(and the corresponding event keyword). C++ has not done the same, at
least not on the syntax level. That said, the introduction of types such as
std::function sure made things a lot simpler for many programming
scenarios.
1
rich Gamma et al., Design Patterns: Elements of Reusable Object-Oriented
E
Software (Boston, MA: Addison Wesley, 1994).
Preliminaries
Who This Book Is For
This book is designed to be a modern-day update to the classic GoF book,
targeting specifically the C++ programming language. I mean, how many
of you are writing Smalltalk out there? Not many; that would be my guess.
The goal of this book is to investigate how we can apply Modern C++
(the latest versions of C++ currently available) to the implementations of
classic design patterns. At the same time, it’s also an attempt to flesh out
any new patterns and approaches that could be useful to C++ developers.
Finally, in some places, this book is quite simply a technology demo for
Modern C++, showcasing how some of its latest features (e.g., coroutines)
make difficult problems a lot easier to solve.
2
Chapter 1 Introduction
3
Chapter 1 Introduction
You should be aware that most of the examples leverage Modern C++
(C++11, 14, 17 and beyond) and generally use the latest C++ language
features that are available to developers. For example, you won’t find
many function signatures ending in -> decltype(...) when C++14
lets us automatically infer the return type. None of the examples target
a particular compiler, but if something doesn’t work with your chosen
compiler,2 you’ll need to find workarounds.
At certain points in time, I will be referencing other programming
languages such as C# or Kotlin. It’s sometimes interesting to note how
designers of other languages have implemented a particular feature. C++
is no stranger to borrowing generally available ideas from other languages:
for example, the introduction of auto and type inference on variable
declarations and return types is present in many other languages.
2
Intel, I’m looking at you!
4
Chapter 1 Introduction
Piracy
Digital piracy is an inescapeable fact of life. A brand new generation is
growing up right now that has never purchased a movie or a book—even
this book. There’s not much that can be done about this. The only thing
I can say is that if you pirated this book, you might not be reading the latest
version.
The joy of online digital publishing is I get to update the book as new
versions of C++ come out and I do more research. So if you paid for this
book, you’ll get free updates in the future as new versions of the C++
language and the Standard Library are released. If not… oh, well.
Important Concepts
Before we begin, I want to briefly mention some key concepts of the C++
world that are going to be referenced in this book.
Now, you might be wondering why one would ever do that? Well,
one reason is to be able to access a typed this pointer inside a base class
implementation.
5
Chapter 1 Introduction
M
ixin Inheritance
In C++, a class can be defined to inherit from its own template argument,
for example:
6
Chapter 1 Introduction
Properties
A property is nothing more than a (typically private) field and a combination
of a getter and a setter. In standard C++, a property looks as follows:
1 class Person
2 {
3 int age;
4 public:
5 int get_age() const { return age; }
6 void set_age(int value) { age = value; }
7 };
1 class Person
2 {
3 int age_;
4 public:
5 int get_age() const { return age_; }
6 void set_age(int value) { age_ = value; }
7 __declspec(property(get=get_age, put=set_age)) int age;
8 };
1 Person person;
2 p.age = 20; // calls p.set_age(20)
7
Chapter 1 Introduction
1 struct Journal
2 {
3 string title;
4 vector<string> entries;
5
6 explicit Journal(const string& title) : title{title} {}
7 };
8
Chapter 1 Introduction
Now, you could add functionality for adding an entry to the journal,
prefixed by the entry’s ordinal number in the journal. This is easy:
9
Chapter 1 Introduction
1 struct PersistenceManager
2 {
3 static void save(const Journal& j, const string& filename)
4 {
5 ofstream ofs(filename);
6 for (auto& s : j.entries)
7 ofs << s << endl;
8 }
9 };
10
Chapter 1 Introduction
Open-Closed Principle
Suppose we have an (entirely hypothetical) range of products in a
database. Each product has a color and size and is defined as:
1 struct ProductFilter
2 {
3 typedef vector<Product*> Items;
4 };
11
Chapter 1 Introduction
Our current approach of filtering items by color is all well and good.
Our code goes into production but, unfortunately, some time later the boss
comes in and asks us to implement filtering by size, too. So we jump back
into ProductFilter.cpp, add the following code and recompile:
This feels like outright duplication, doesn’t it? Why don’t we just write
a general method that takes a predicate (some function)? Well, one reason
could be that different forms of filtering can be done in different ways: for
example, some record types might be indexed and need to be searched in
a specific way; some data types are amenable to search on a GPU, while
others are not.
12
Chapter 1 Introduction
Our code goes into production but, once again, the boss comes back
and tells us that now there’s a need to search by both color and size. So
what are we to do but add another function?
1 ProductFilter::Items ProductFilter::by_color_and_size(Items
2 items, Size size, Color color)
3 {
4 Items result;
5 for (auto& i : items)
6 if (i->size == size && i->color == color)
7 result.push_back(i);
8 return result;
9 }
13
Chapter 1 Introduction
Again, all we are doing is specifying the signature for a function called
filter which takes all the items and a specification, and returns all items
that conform to the specification. There is an assumption that the items
are stored as a vector<T*>, but in reality you could pass filter() either
a pair of iterators or some custom-made interface designed specifically
for going through a collection. Regrettably, the C++ language has failed to
standardize the notion of an enumeration or collection, something that
exists in other programming languages (e.g., .NET’s IEnumerable).
Based on the preceding, the implementation of an improved filter is
really simple:
14
Chapter 1 Introduction
10 result.push_back(p);
11 return result;
12 }
13 };
Armed with this specification, and given a list of products, we can now
filter them as follows:
15
Chapter 1 Introduction
8 ColorSpecification green(Color::Green);
9
10 auto green_things = bf.filter(all, green);
11 for (auto& x : green_things)
12 cout << x->name << " is green" << endl;
The preceding gets us “Apple” and “Tree” because they are both green.
Now, the only thing we haven’t implemented so far is searching for size
and color (or, indeed, explained how you would search for size or color,
or mix different criteria). The answer is that you simply make a composite
specification. For example, for the logical AND, you can make it as follows:
16
Discovering Diverse Content Through
Random Scribd Documents
Fritz quickly brought one, and, having formed rollers by cutting up
a long spar, I raised the fore part of my boat with the bar, and my
sons placed a roller under it.
"How is it, father," inquired Ernest, "that with that thing you alone
can do more than all of us together?"
I explained, as well as I could in a hurry, the principle of the lever;
and promised to have a long talk on the subject of Mechanics,
should we have a future opportunity.
I now made fast a long rope to the stern of our boat, attaching
the other end to a beam; then placing a second and third roller
under it, we once more began to push, this time with success, and
soon our gallant craft was safely launched: so swiftly indeed did she
glide into the water that, but for the rope, she would have passed
beyond our reach. The boys wished to jump in directly; but, alas,
she leaned so much on one side that they could not venture to do
so.
Some heavy things being thrown in, however, the boat righted
itself by degrees, and the boys were so delighted that they struggled
which should first leap in to have the fun of sitting down in the tubs.
But it was plain to me at once that something more was required to
make her perfectly safe, so I contrived out-riggers to preserve the
balance, by nailing long poles across at the stem and stern, and
fixing at the end of each empty brandy casks. Then the boat
appearing steady, I got in; and turning it toward the most open side
of the wreck, I cut and cleared away obstructions, so as to leave a
free passage for our departure, and the boys brought oars to be
ready for the voyage. This important undertaking we were forced to
postpone until the next day, as it was by this time far too late to
attempt it. It was not pleasant to have to spend another night in so
precarious a situation; but yielding to necessity, we sat down to
enjoy a comfortable supper, for during our exciting and incessant
work all day we had taken nothing but an occasional biscuit and a
little wine.
We prepared for rest in a much happier frame of mind than on the
preceding day, but I did not forget the possibility of a renewed
storm, and therefore made every one put on the belts as before.
I persuaded my wife (not without considerable difficulty), to put
on a sailor's dress, assuring her she would find it much more
comfortable and convenient for all she would have to go through.
She at last consented to do this, and left us for a short time,
reappearing with much embarrassment and many blushes, in a most
becoming suit, which she had found in a midshipman's chest. We all
admired her costume, and any awkwardness she felt soon began to
pass off; then retiring to our berths, peaceful sleep prepared us all
for the exertions of the coming day.
We rose up betimes, for sleep weighs lightly on the hopeful, as
well as on the anxious. After kneeling together in prayer, "Now, my
beloved ones," said I, "with God's help we are about to effect our
escape. Let the poor animals we must leave behind be well fed, and
put plenty of fodder within their reach: in a few days we may be
able to return, and save them likewise. After that, collect everything
you can think of which may be of use to us."
The boys joyfully obeyed me, and I selected from the large
quantity of stores they got together, canvas to make a tent, a chest
of carpenter's tools, guns, pistols, powder, shot, and bullets, rods
and fishing tackle, an iron pot, a case of portable soup, and another
of biscuit. These useful articles, of course, took the place of the
ballast I had hastily thrown in the day before.
With a hearty prayer for God's blessing, we now began to take our
seats, each in his tub. Just then we heard the cocks begin to crow,
as though to reproach us for deserting them. "Why should not the
fowls go with us!" exclaimed I. "If we find no food for them, they
can be food for us!" Ten hens and a couple of cocks were
accordingly placed in one of the tubs, and secured with some wire-
netting over them.
The ducks and geese were set at liberty, and took to the water at
once, while the pigeons, rejoicing to find themselves on the wing,
swiftly made for the shore. My wife, who managed all this for me,
kept us waiting for her some little time, and came at last with a bag
as big as a pillow in her arms. "This is my contribution," said she,
throwing the bag to little Franz, to be, as I thought, a cushion for
him to sit upon.
All being ready, we cast off, and moved away from the wreck. My
good, brave wife sat in the first compartment of the boat; next her
was Franz, a pretty little boy, nearly eight years old. Then came
Fritz, a handsome, spirited young fellow of fifteen; the two center
tubs contained the valuable cargo; then came our bold, thoughtless
Jack; next him Ernest, my second son, intelligent, well-formed, and
rather indolent. I myself, the anxious, loving father, stood in the
stern, endeavoring to guide the raft with its precious burden to a
safe landing-place.
The elder boys took the oars; every one wore a float belt, and had
something useful close to him in case of being thrown into the water.
The tide was flowing, which was a great help to the young
oarsmen. We emerged from the wreck and glided into the open sea.
All eyes were strained to get a full view of the land, and the boys
pulled with a will; but for some time we made no progress, as the
boat kept turning round and round, until I hit upon the right way to
steer it, after which we merrily made for the shore.
We had left two dogs, Turk and Juno, on the wreck, as being both
large mastiffs we did not care to have their additional weight on
board our craft; but when they saw us apparently deserting them,
they set up a piteous howl, and sprang into the sea. I was sorry to
see this, for the distance to the land was so great that I scarcely
expected them to be able to accomplish it. They followed us,
however, and occasionally resting their fore-paws on the out-riggers,
kept up with us well. Jack was inclined to deny them this, their only
chance of safety. "Stop," said I, "that would be unkind as well as
foolish; remember, the merciful man regardeth the life of his beast."
Our passage, though tedious, was safe; but the nearer we
approached the shore the less inviting it appeared; the barren rocks
seemed to threaten us with misery and want.
Many casks, boxes, and bales of goods floated on the water
around us. Fritz and I managed to secure a couple of hogsheads, so
as to tow them alongside. With the prospect of famine before us, it
was desirable to lay hold of anything likely to contain provisions.
By and by we began to perceive that, between and beyond the
cliffs, green grass and trees were discernible. Fritz could distinguish
many tall palms, and Ernest hoped they would prove to be cocoanut
trees, and enjoyed the thoughts of drinking the refreshing milk.
"I am very sorry I never thought of bringing away the captain's
telescope," said I.
"Oh, look here, father!" cried Jack, drawing a little spyglass
joyfully out of his pocket.
By means of this glass, I made out that at some distance to the
left the coast was much more inviting; a strong current however,
carried us directly toward the frowning rocks, but I presently
observed an opening, where a stream flowed into the sea, and saw
that our geese and ducks were swimming toward this place. I
steered after them into the creek, and we found ourselves in a small
bay or inlet where the water was perfectly smooth and of moderate
depth. The ground sloped gently upward from the low banks to the
cliffs, which here retired inland, leaving a small plain, on which it
was easy for us to land. Every one sprang gladly out of the boat but
little Franz, who, lying packed in his tub like a potted shrimp, had to
be lifted out by his mother.
The dogs had scrambled on shore before us; they received us with
loud barking and the wildest demonstrations of delight. The geese
and ducks kept up an incessant din, added to which was the
screaming and croaking of flamingoes and penguins, whose
dominion we were invading. The noise was deafening, but far from
unwelcome to me, as I thought of the good dinners the birds might
furnish.
As soon as we could gather our children around us on dry land,
we knelt to offer thanks and praise for our merciful escape, and with
full hearts we commended ourselves to God's good keeping for the
time to come.
All hands then briskly fell to the work of unloading, and oh, how
rich we felt ourselves as we did so! The poultry we left at liberty to
forage for themselves, and set about finding a suitable place to erect
a tent in which to pass the night. This we speedily did; thrusting a
long spar into a hole in the rock, and supporting the other end by a
pole firmly planted in the ground, we formed a framework over
which we stretched the sailcloth we had brought; besides fastening
this down with pegs, we placed our heavy chest and boxes on the
border of the canvas, and arranged hooks so as to be able to close
up the entrance during the night.
When this was accomplished, the boys ran to collect moss and
grass, to spread in the tent for our beds, while I arranged a fireplace
with some large flat stones, near the brook which flowed close by.
Dry twigs and seaweed were soon in a blaze on the hearth; I filled
the iron pot with water, and giving my wife several cakes of the
portable soup, she established herself as our cook, with little Franz
to help her.
He, thinking his mother was melting some glue for carpentering,
was eager to know "what papa was going to make next?"
"This is to be soup for your dinner, my child. Do you think these
cakes look like glue?"
"Yes, indeed I do!" replied Franz, "and I should not much like to
taste glue soup! don't you want some beef or mutton, mamma?"
"Where can I get it, dear!" said she, "we are a long way from a
butcher's shop! but these cakes are made of the juice of good meat,
boiled till it becomes a strong, stiff jelly—people take them when
they go to sea, because on a long voyage they can only have salt
meat, which will not make nice soup."
Fritz, meanwhile, leaving a loaded gun with me, took another
himself, and went along the rough coast to see what lay beyond the
stream; this fatiguing sort of walk not suiting Ernest's fancy, he
sauntered down to the beach, and Jack scrambled among the rocks,
searching for shell-fish.
I was anxious to land the two casks which were floating alongside
our boat, but on attempting to do so, I found that I could not get
them up the bank on which we had landed, and was therefore
obliged to look for a more convenient spot. As I did so, I was
startled by hearing Jack shouting for help, as though in great
danger. He was at some distance, and I hurried toward him with a
hatchet in my hand. The little fellow stood screaming in a deep pool,
and as I approached, I saw that a huge lobster had caught his leg in
its powerful claw. Poor Jack was in a terrible fright; kick as he would,
his enemy still clung on. I waded into the water, and seizing the
lobster firmly by the back, managed to make it loosen its hold, and
we brought it safe to land. Jack, having speedily recovered his
spirits, and anxious to take such a prize to his mother, caught the
lobster in both hands, but instantly received such a severe blow from
its tail that he flung it down, and passionately hit the creature with a
large stone. This display of temper vexed me. "You are acting in a
very childish way, my son," said I; "never strike an enemy in a
revengeful spirit." Once more lifting the lobster, Jack ran
triumphantly toward the tent.
"Mother, mother! a lobster, Ernest! look here, Franz! mind, he'll
bite you! Where's Fritz?" All came crowding round Jack and his prize,
wondering at its unusual size, and Ernest wanted his mother to
make lobster soup directly, by adding it to what she was now boiling.
She, however, begged to decline making any such experiment,
and said she preferred cooking one dish at a time. Having remarked
that the scene of Jack's adventure afforded a convenient place for
getting my casks on shore, I returned thither and succeeded in
drawing them up on the beach, where I set them on end, and for
the present left them.
On my return I resumed the subject of Jack's lobster, and told him
he should have the offending claw all to himself, when it was ready
to be eaten, congratulating him on being the first to discover
anything useful.
"As to that," said Ernest, "I found something very good to eat, as
well as Jack, only I could not get at them without wetting my feet."
"Pooh!" cried Jack, "I know what he saw—nothing but some nasty
mussels; I saw them too. Who wants to eat trash like that! Lobster
for me!"
"I believe them to be oysters, not mussels," returned Ernest
calmly.
"Be good enough, my philosophical young friend, to fetch a few
specimens of these oysters in time for our next meal," said I; "we
must all exert ourselves, Ernest, for the common good, and pray
never let me hear you object to wetting your feet. See how quickly
the sun has dried Jack and me."
"I can bring some salt at the same time," said Ernest, "I remarked
a good deal lying in the crevices of the rocks; it tasted very pure and
good, and I concluded it was produced by the evaporation of sea
water in the sun."
"Extremely probable, learned sir," cried I; "but if you had brought
a bagful of this good salt instead of merely speculating so profoundly
on the subject, it would have been more to the purpose. Run and
fetch some directly."
It proved to be salt sure enough, although so impure that it
seemed useless, till my wife dissolved and strained it, when it
became fit to put in the soup.
"Why not use the sea water itself?" asked Jack.
"Because," said Ernest, "it is not only salt, but bitter too. Just try
it."
"Now," said my wife, tasting the soup with the stick with which
she had been stirring it, "dinner is ready, but where can Fritz be?"
she continued, a little anxiously.
"How are we to eat our soup when he does come?" I asked; "we
have neither plates nor spoons, and we can scarcely lift the boiling
pot to our mouths. We are in as uncomfortable a position as was the
fox to whom the stork served up a dinner in a jug with a long neck."
"Oh, for a few cocoanut shells!" sighed Ernest.
"Oh, for half a dozen plates and as many silver spoons!" rejoined
I, smiling.
"Really though, oyster-shells would do," said he, after a moment's
thought.
"True, that is an idea worth having! Off with you, my boys; get the
oysters and clean out a few shells. What though our spoons have no
handles, and we do burn our fingers a little in baling the soup out."
Jack was away and up to his knees in the water, in a moment,
detaching the oysters. Ernest followed more leisurely, and still
unwilling to wet his feet, stood by the margin of the pool and
gathered in his handkerchief the oysters his brother threw him; as
he thus stood he picked up and pocketed a large mussel shell for his
own use. As they returned with a good supply we heard a shout
from Fritz in the distance; we returned it joyfully, and he presently
appeared before us, his hands behind his back, and a look of
disappointment upon his countenance.
"Unsuccessful!" said he.
"Really!" I replied; "never mind, my boy, better luck next time."
"Oh, Fritz!" exclaimed his brothers, who had looked behind him, "a
sucking-pig, a little sucking-pig. Where did you get it? How did you
shoot it? Do let us see it!"
Fritz then with sparkling eyes exhibited his prize.
"I am glad to see the results of your prowess, my boy," said I;
"but I cannot approve of deceit, even as a joke; stick to the truth in
jest and earnest."
Fritz then told us how he had been to the other side of the
stream. "So different from this," he said; "it is really a beautiful
country, and the shore, which runs down to the sea in a gentle
slope, is covered with all sorts of useful things from the wreck. Do
let us go and collect them. And, father, why should we not return to
the wreck and bring off some of the animals? Just think of what
value the cow would be to us, and what a pity it would be to lose
her! Let us get her on shore, and we will move over the stream,
where she will have good pasturage, and we shall be in the shade
instead of on this desert, and father, I do wish——"
"Stop, stop, my boy!" cried I. "All will be done in good time. To-
morrow and the day after will bring work of their own. And tell me,
did you see no traces of our shipmates?"
"Not a sign of them, either on land or sea, living or dead," he
replied.
"But the sucking-pig," said Jack, "where did you get it?"
"It was one of several," said Fritz, "which I found on the shore;
most curious animals they are; they hopped rather than walked, and
every now and then would squat down on their legs and rub their
snouts with their fore-paws. Had not I been afraid of losing them all,
I would have tried to catch one alive, they seemed so tame."
Meanwhile Ernest had been carefully examining the animal in
question.
"This is no pig," he said; "and except for its bristly skin, does not
look like one. See, its teeth are not like those of a pig, but rather
those of a squirrel. In fact," he continued, looking at Fritz, "your
sucking-pig is an agouti."
"Dear me," said Fritz; "listen to the great professor lecturing! He is
going to prove that a pig is not a pig!"
"You need not be so quick to laugh at your brother," said I, in my
turn; "he is quite right. I, too, know the agouti by descriptions and
pictures, and there is little doubt that this is a specimen. The little
animal is a native of North America, where it makes its nest under
the roots of trees, and lives upon fruit. But, Ernest, the agouti not
only looks something like a pig, but most decidedly grunts like a
porker."
While we were thus talking, Jack had been vainly endeavoring to
open an oyster with his large knife. "Here is a simpler way," said I,
placing an oyster on the fire; it immediately opened. "Now," I
continued, "who will try this delicacy?" All at first hesitated to
partake of them, so unattractive did they appear. Jack, however,
tightly closing his eyes and making a face as though about to take
medicine, gulped one down. We followed his example, one after the
other, each doing so rather to provide himself with a spoon than with
any hope of cultivating a taste for oysters.
Our spoons were now ready, and gathering round the pot we
dipped them in, not, however, without sundry scalded fingers. Ernest
then drew from his pocket the large shell he had procured for his
own use, and scooping up a good quantity of soup he put it down to
cool, smiling at his own foresight.
"Prudence should be exercised for others," I remarked; "your cool
soup will do capitally for the dogs, my boy; take it to them, and then
come and eat like the rest of us."
Ernest winced at this, but silently taking up his shell he placed it
on the ground before the hungry dogs, who lapped up its contents
in a moment; he then returned, and we all went merrily on with our
dinner. While we were thus busily employed, we suddenly discovered
that our dogs, not satisfied with their mouthful of soup, had espied
the agouti, and were rapidly devouring it. Fritz, seizing his gun, flew
to rescue it from their hungry jaws, and before I could prevent him,
struck one of them with such force that his gun was bent. The poor
beasts ran off howling, followed by a shower of stones from Fritz,
who shouted and yelled at them so fiercely that his mother was
actually terrified. I followed him, and as soon as he would listen to
me, represented to him how despicable, as well as wicked, was such
an outbreak, of temper: "for," said I, "you have hurt, if not actually
wounded, the dogs; you have distressed and terrified your mother,
and spoiled your gun."
Though Fritz's passion was easily aroused, it never lasted long,
and speedily recovering himself, immediately he entreated his
mother's pardon, and expressed his sorrow for his fault.
By this time the sun was sinking beneath the horizon, and the
poultry, which had been straying to some little distance, gathered
round us, and began to pick up the crumbs of biscuit which had
fallen during our repast. My wife hereupon drew from her mysterious
bag some handfuls of oats, peas, and other grain, and with them
began to feed the poultry. She at the same time showed me several
other seeds of various vegetables. "That was indeed thoughtful,"
said I; "but pray be careful of what will be of such value to us; we
can bring plenty of damaged biscuits from the wreck, which, though
of no use as food for us, will suit the fowls very well indeed."
The pigeons now flew up to crevices in the rocks, the fowls
perched themselves on our tent pole, and the ducks and geese
waddled off, cackling and quacking, to the marshy margin of the
river. We, too, were ready for repose, and having loaded our guns,
and offered up our prayers to God, thanking Him for His many
mercies to us, we commended ourselves to His protecting care, and
as the last ray of light departed, closed our tent and lay down to
rest.
The children remarked the suddenness of nightfall, for indeed
there had been little or no twilight. This convinced me that we must
be not far from the equator, for twilight results from the refraction of
the sun's rays: the more obliquely these rays fall, the farther does
the partial light extend; while the more perpendicularly they strike
the earth, the longer do they continue their undiminished force,
until, when the sun sinks, they totally disappear, thus producing
sudden darkness.
CHAPTER II.
We should have been badly off without the shelter of our tent, for
the night proved as cold as the day had been hot, but we managed
to sleep comfortably, every one being thoroughly fatigued by the
labors of the day. The voice of our vigilant cock, which, as he loudly
saluted the rising moon, was the last sound I heard at night, roused
me at daybreak, and I then awoke my wife, that in the quiet interval
while yet our children slept, we might take counsel together on our
situation and prospects. It was plain to both of us that, in the first
place, we should ascertain if possible the fate of our late
companions, and then examine into the nature and resources of the
country on which we were stranded.
We therefore came to the resolution that, as soon as we had
breakfasted, Fritz and I should start on an expedition with these
objects in view, while my wife remained near our landing-place with
the three younger boys.
"Rouse up, rouse up, my boys," cried I, awakening the children
cheerfully. "Come and help your mother to get breakfast ready."
"As to that," said she smiling, "we can but set on the pot, and boil
some more soup!"
"Why, you forget Jack's fine lobster!" replied I. "What has become
of it, Jack?"
"It has been safe in this hole in the rock all night, father. You see,
I thought, as the dogs seem to like good things, they might take a
fancy to that, as well as to the agouti."
"A very sensible precaution," remarked I. "I believe even my
heedless Jack will learn wisdom in time. It is well the lobster is so
large, for we shall want to take part with us on our excursion to-
day."
At the mention of an excursion, the four children were wild with
delight, and capering around me, clapped their hands for joy.
"Steady there, steady!" said I, "you cannot expect all to go. Such
an expedition as this would be too dangerous and fatiguing for you
younger ones. Fritz and I will go alone this time, with one of the
dogs, leaving the other to defend you."
We then armed ourselves, each taking a gun and a game bag;
Fritz in addition sticking a pair of pistols in his belt, and I a small
hatchet in mine; breakfast being over, we stowed away the
remainder of the lobster and some biscuits, with a flask of water,
and were ready for a start.
"Stop!" I exclaimed, "we have still left something very important
undone."
"Surely not," said Fritz.
"Yes," said I, "we have not yet joined in morning prayer. We are
only too ready, amid the cares and pleasures of this life, to forget
the God to whom we owe all things." Then having commended
ourselves to his protecting care, I took leave of my wife and
children, and bidding them not wander far from the boat and tent,
we parted not without some anxiety on either side, for we knew not
what might assail us in this unknown region.
We now found that the banks of the stream were on both sides so
rocky that we could get down to the stream by only one narrow
passage, and there was no corresponding path on the other side. I
was glad to see this, however, for I now knew that my wife and
children were on a comparatively inaccessible spot, the other side of
the tent being protected by steep and precipitous cliffs. Fritz and I
pursued our way up the stream until we reached a point where the
waters fell from a considerable height in a cascade, and where
several large rocks lay half covered by the water; by means of these
we succeeded in crossing the stream in safety. We thus had the sea
on our left, and a long line of rocky heights, here and there adorned
with clumps of trees, stretching away inland to the right. We had
forced our way scarcely fifty yards through the long rank grass,
which was here partly withered by the sun and much tangled, when
we heard behind us a rustling, and on looking round saw the grass
waving to and fro, as if some animal were passing through it. Fritz
instantly turned and brought his gun to his shoulder, ready to fire
the moment the beast should appear. I was much pleased with my
son's coolness and presence of mind, for it showed me that I might
thoroughly rely upon him on any future occasion when real danger
might occur; this time, however, no savage beast rushed out, but
our trusty dog Turk, whom in our anxiety at parting we had
forgotten, and who had been sent after us, doubtless, by my
thoughtful wife.
From this little incident, however, we saw how dangerous was our
position, and how difficult escape would be should any fierce beast
steal upon us unawares: we therefore hastened to make our way to
the open seashore. Here the scene which presented itself was
indeed delightful. A background of hills, the green waving grass, the
pleasant groups of trees stretching here and there to the very
water's edge, formed a lovely prospect. On the smooth sand we
searched carefully for any trace of our hapless companions, but not
the mark of a footstep could we find.
"Shall I fire a shot or two?" said Fritz; "that would bring our
companions, if they are within hearing."
"It would indeed," I said, "or any savages that may be here. No,
no; let us search diligently, but as quietly as possible."
"But why, father, should we trouble ourselves about them at all?
They left us to shift for ourselves, and I for one don't care to set
eyes on them again."
"You are wrong, my boy," said I. "In the first place, we should not
return evil for evil; then, again, they might be of great assistance to
us in building a house of some sort; and lastly, you must remember
that they took nothing with them from the vessel, and may be
perishing of hunger."
Thus talking, we pushed on until we came to a pleasant grove
which stretched down to the water's edge; here we halted to rest,
seating ourselves under a large tree, by a rivulet which murmured
and splashed along its pebbly bed into the great ocean before us. A
thousand gayly-plumaged birds flew twittering above us, and Fritz
and I gazed up at them.
My son suddenly started up.
"A monkey," he exclaimed; "I am nearly sure I saw a monkey."
As he spoke he sprang round to the other side of the tree, and in
doing so stumbled over a round substance, which he handed to me,
remarking, as he did so, that it was a round bird's nest, of which he
had often heard.
"You may have done so," said I, laughing, "but you need not
necessarily conclude that every round hairy thing is a bird's nest;
this, for instance, is not one, but a cocoanut."
We split open the nut, but, to our disgust, found the kernel dry
and uneatable.
"Hullo," cried Fritz, "I always thought a cocoanut was full of
delicious sweet liquid, like almond milk."
"So it is," I replied, "when young and fresh, but as it ripens the
milk becomes congealed, and in course of time is solidified into a
kernel. This kernel then dries as you see here, but when the nut falls
on favorable soil, the germ within the kernel swells until it bursts
through the shell, and, taking root, springs up a new tree."
"I do not understand," said Fritz, "how the little germ manages to
get through this great thick shell, which is not like an almond or
hazel nutshell, that is divided down the middle already."
"Nature provides for all things," I answered, taking up the pieces.
"Look here, do you see these three round holes near the stalk? it is
through them that the germ obtains egress. Now let us find a good
nut if we can."
As cocoanuts must be over-ripe before they fall naturally from the
tree, it was not without difficulty that we obtained one in which the
kernel was not dried up. When we succeeded, however, we were so
refreshed by the fruit that we could defer the repast we called our
dinner until later in the day, and so spare our stock of provisions.
Continuing our way through a thicket, and which was so densely
overgrown with lianas that we had to clear a passage with our
hatchets, we again emerged on the seashore beyond, and found an
open view, the forest sweeping inland, while on the space before us
stood at intervals single trees of remarkable appearance.
These at once attracted Fritz's observant eye, and he pointed, to
them, exclaiming,
"Oh, what absurd-looking trees, father! See what strange bumps
there are on the trunks."
We approached to examine them, and I recognized them as
calabash trees, the fruit of which grows in this curious way on the
stems, and is a species of gourd, from the hard rind of which bowls,
spoons, and bottles can be made. "The savages," I remarked, "are
said to form these things most ingeniously, using them to contain
liquids: indeed, they actually cook food in them."
"Oh, but that is impossible," returned Fritz. "I am quite sure this
rind would be burnt through directly it was set on the fire."
"I did not say it was set on the fire at all. When the gourd has
been divided in two, and the shell or rind emptied of its contents, it
was filled with water, into which the fish, or whatever is to be
cooked, is put; red hot stones are added until the water boils; the
food becomes fit to eat, and the gourd-rind remains uninjured."
"That is a very clever plan: very simple too. I daresay I should
have hit on it, if I had tried," said Fritz.
"The friends of Columbus thought it very easy to make an egg
stand upon its end when he had shown them how to do it. But now
suppose we prepare some of these calabashes, that they may be
ready for use when we take them home."
Fritz instantly took up one of the gourds, and tried to split it
equally with his knife, but in vain: the blade slipped, and the
calabash was cut jaggedly. "What a nuisance!" said Fritz, flinging it
down, "the thing is spoiled; and yet it seemed so simple to divide it
properly."
"Stay," said I; "you are too impatient, those pieces are not
useless. Do you try to fashion from them a spoon or two while I
provide a dish."
I then took from my pocket a piece of string, which I tied tightly
round a gourd, as near one end of it as I could; then tapping the
string with the back of my knife, it penetrated the outer shell. When
this was accomplished, I tied the string yet tighter; and drawing the
ends with all my might, the gourd fell, divided exactly as I wished.
"That is clever!" cried Fritz. "What in the world put that plan into
your head?"
"It is a plan," I replied, "which the negroes adopt, as I have
learned from reading books of travel."
"Well, it certainly makes a capital soup-tureen, and a soup-plate
too," said Fritz, examining the gourd. "But supposing you had
wanted to make a bottle, how would you have set to work?"
"It would be an easier operation than this, if possible. All that is
necessary is to cut a round hole at one end, then to scoop out the
interior, and to drop in several shot or stones; when these are
shaken, any remaining portions of the fruit are detached, and the
gourd is thoroughly cleaned, and the bottle completed."
"That would not make a very convenient bottle though, father; it
would be more like a barrel."
"True, my boy; if you want a more shapely vessel, you must take
it in hand when it is younger. To give it a neck, for instance, you
must tie a bandage round the young gourd while it is still on the
tree, and then all will swell but that part which you have checked."
As I spoke, I filled the gourds with sand, and left them to dry;
marking the spot that we might return for them on our way back.
For three hours or more we pushed forward, keeping a sharp
lookout on either side for any trace of our companions, till we
reached a bold promontory, stretching some way into the sea, from
whose rocky summit I knew that we should obtain a good and
comprehensive view of the surrounding country. With little difficulty
we reached the top, but the most careful survey of the beautiful
landscape failed to show us the slightest sign or trace of human
beings. Before us stretched a wide and lovely bay, fringed with
yellow sands, either side extending into the distance, and almost lost
to view in two shadowy promontories; inclosed by these two arms
lay a sheet of rippling water, which reflected in its depths the
glorious sun above. The scene inland was no less beautiful; and yet
Fritz and I both felt a shade of loneliness stealing over us as we
gazed on its utter solitude.
"Cheer up, Fritz, my boy," said I presently. "Remember that we
chose a settler's life long ago, before we left our own dear country;
we certainly did not expect to be so entirely alone—but what
matters a few people, more or less? With God's help, let us endeavor
to live here contentedly, thankful that we were not cast upon some
bare and inhospitable island. But come, the heat here is getting
unbearable; let us find some shady place before we are completely
broiled away."
We descended the hill and made for a clump of palm trees, which
we saw at a little distance. To reach this, we had to pass through a
dense thicket of reeds, no pleasant or easy task; for, besides the
difficulty of forcing our way through, I feared at every step that we
might tread on some venomous snake. Sending Turk in advance, I
cut one of the reeds, thinking it would be a more useful weapon
against a reptile than my gun. I had carried it but a little way, when
I noticed a thick juice exuding from one end. I tasted it, and to my
delight found it sweet and pleasant. I at once knew that I was
standing amongst sugar-canes. Wishing Fritz to make the same
discovery, I advised him to cut a cane for his defense; he did so, and
as he beat the ground before him, the reed split, and his hand was
covered with the juice. He carefully touched the cane with the tip of
his tongue, then, finding the juice sweet, he did so again with less
hesitation; and a moment afterward sprang back to me exclaiming:
"Oh, father, sugar-canes! sugar-canes! Taste it. Oh, how delicious,
how delightful! do let us take a lot home to mother," he continued,
sucking eagerly at the cane.
"Gently there," said I, "take breath a moment, moderation in all
things, remember. Cut some to take home if you like, only don't take
more than you can conveniently carry."
In spite of my warning, my son cut a dozen or more of the largest
canes, and stripping them of their leaves, carried them under his
arm. We then pushed through the cane-brake, and reached the
clump of palms for which we had been making; as we entered it a
troop of monkeys, who had been disporting themselves on the
ground, sprang up, chattering and grimacing, and before we could
clearly distinguish them were at the very top of the trees.
Fritz was so provoked by their impertinent gestures that he raised
his gun and would have shot one of the poor beasts.
"Stay," cried I, "never take the life of any animal needlessly. A live
monkey up in that tree is of more use to us than a dozen dead ones
at our feet, as I will show you."
Saying this, I gathered a handful of small stones, and threw them
up toward the apes. The stones did not go near them, but
influenced by their instinctive mania for imitation, they instantly
seized all the cocoanuts within their reach, and sent a perfect hail of
them down upon us.
Fritz was delighted with my stratagem, and rushing forward picked
up some of the finest of the nuts. We drank the milk they contained,
drawing it through the holes, which I pierced, and then, splitting the
nuts open with the hatchet, ate the cream which lined their shells.
After this delicious meal, we thoroughly despised the lobster we had
been carrying, and threw it to Turk, who ate it gratefully; but far
from being satisfied, the poor beast began to gnaw the ends of the
sugar-canes, and to beg for cocoanut. I slung a couple of the nuts
over my shoulder, fastening them together by their stalks, and Fritz
having resumed his burden, we began our homeward march.
I soon discovered that Fritz found the weight of his canes
considerably more than he expected: he shifted them from shoulder
to shoulder, then for a while carried them under his arm, and finally
stopped short with a sigh. "I had no idea," he said, "that a few reeds
would be so heavy."
"Never mind, my boy," I said, "patience and courage! Do you not
remember the story of Æsop and his breadbasket, how heavy he
found it when he started, and how light at the end of his journey?
Let us each take a fresh staff, and then fasten the bundle crosswise
with your gun."
We did so, and once more stepped forward. Fritz presently noticed
that I from time to time sucked the end of my cane.
"Oh, come," said he, "that's a capital plan of yours, father, I'll do
that too."
So saying, he began to suck most vigorously, but not a drop of the
juice could he extract. "How is this?" he asked. "How do you get the
juice out, father?"
"Think a little," I replied, "you are quite as capable as I am of
finding out the way, even if you do not know the real reason of your
failure."
"Oh, of course," said he, "it is like trying to suck marrow from a
marrow-bone, without making a hole at the other end."
"Quite right," I said, "you form a vacuum in your mouth and the
end of your tube, and expect the air to force down the liquid from
the other end which it cannot possibly enter."
Fritz was speedily perfect in the accomplishment of sucking sugar-
cane, discovering by experience the necessity for a fresh cut at each
joint or knot in the cane, through which the juice would not flow; he
talked of the pleasure of initiating his brothers in the art, and of how
Ernest would enjoy the cocoanut milk, with which he had filled his
flask.
"My dear boy," said I, "you need not have added that to your load;
the chances are it is vinegar by the time we get home. In the heat of
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.
textbookfull.com