100% found this document useful (2 votes)
83 views

Learn C++ by Example: Covers Versions 11 to 23 (Final Release) 1 / converted Edition Frances Buontempo download

Learn C++ by Example is a comprehensive guide that covers C++ versions 11 to 23, designed to help readers understand modern C++ features through practical examples. The book includes various projects and exercises that introduce concepts like smart pointers, ranges, and coroutines, making it suitable for both beginners and those returning to C++. It emphasizes learning by doing, encouraging readers to compile and run code as they progress through the material.

Uploaded by

rodenleddy0w
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
83 views

Learn C++ by Example: Covers Versions 11 to 23 (Final Release) 1 / converted Edition Frances Buontempo download

Learn C++ by Example is a comprehensive guide that covers C++ versions 11 to 23, designed to help readers understand modern C++ features through practical examples. The book includes various projects and exercises that introduce concepts like smart pointers, ranges, and coroutines, making it suitable for both beginners and those returning to C++. It emphasizes learning by doing, encouraging readers to compile and run code as they progress through the material.

Uploaded by

rodenleddy0w
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Learn C++ by Example: Covers Versions 11 to 23

(Final Release) 1 / converted Edition Frances


Buontempo download

https://textbookfull.com/product/learn-c-by-example-covers-
versions-11-to-23-final-release-1-converted-edition-frances-
buontempo/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Primary Mathematics Textbook 2B Jennifer Hoerst

https://textbookfull.com/product/primary-mathematics-
textbook-2b-jennifer-hoerst/

Handbook of Macroeconomics, Volume 2A-2B SET 1st


Edition John B. Taylor

https://textbookfull.com/product/handbook-of-macroeconomics-
volume-2a-2b-set-1st-edition-john-b-taylor/

Deep Dive into Power Automate: Learn by Example 1st


Edition Mishra

https://textbookfull.com/product/deep-dive-into-power-automate-
learn-by-example-1st-edition-mishra/

Blender 3D Printing by Example Learn to use Blender s


modeling tools for 3D printing by creating 4 projects
1st Edition Vicky Somma

https://textbookfull.com/product/blender-3d-printing-by-example-
learn-to-use-blender-s-modeling-tools-for-3d-printing-by-
creating-4-projects-1st-edition-vicky-somma/
Genetic Algorithms and Machine Learning for Programmers
Create AI Models and Evolve Solutions 1st Edition
Frances Buontempo

https://textbookfull.com/product/genetic-algorithms-and-machine-
learning-for-programmers-create-ai-models-and-evolve-
solutions-1st-edition-frances-buontempo/

ANSI C Programming Learn ANSI C Step by Step 1st


Edition Yashavant Kanetkar

https://textbookfull.com/product/ansi-c-programming-learn-ansi-c-
step-by-step-1st-edition-yashavant-kanetkar/

Unity 2018 By Example Learn about game and virtual


reality development by creating five engaging projects
Second Edition Alan Thorn

https://textbookfull.com/product/unity-2018-by-example-learn-
about-game-and-virtual-reality-development-by-creating-five-
engaging-projects-second-edition-alan-thorn/

JavaFX 9 by Example Dea

https://textbookfull.com/product/javafx-9-by-example-dea/

Blazor WebAssembly By Example Second Edition --

https://textbookfull.com/product/blazor-webassembly-by-example-
second-edition/
inside front cover
This book uses std::cin, std::cout, std::vector, and
std::string in many places. These should be old, familiar C++
features. By counting other features from the standard namespace in
the code with this book, we can form a word cloud. The larger the
word, the more often we use it. See if you recognize any, and look
back when you have finished the book to remind yourself what you
have learned.
Learn C++ by Example

COVERS VERSIONS 11 TO 23

Frances Buontempo

FOREWORD BY MATT GODBOLT

To comment go to liveBook

Manning

Shelter Island
For more information on this and other Manning titles go to
www.manning.com
Copyright

For online information and ordering of these and other


Manning books, please visit www.manning.com. The
publisher offers discounts on these books when ordered in
quantity.

For more information, please contact

Special Sales Department


Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com

©2024 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a


retrieval system, or transmitted, in any form or by means
electronic, mechanical, photocopying, or otherwise, without
prior written permission of the publisher.

Many of the designations used by manufacturers and sellers


to distinguish their products are claimed as trademarks.
Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the
designations have been printed in initial caps or all caps.
♾ Recognizing the importance of preserving what has been
written, it is Manning’s policy to have the books we publish
printed on acid-free paper, and we exert our best efforts to
that end. Recognizing also our responsibility to conserve the
resources of our planet, Manning books are printed on paper
that is at least 15 percent recycled and processed without the
use of elemental chlorine.

Manning Publications Co.


20 Baldwin Road Technical
PO Box 761
Shelter Island, NY 11964

Development editor: Doug Rudder


Review editor: Adriana Sabo/Dunja Nikitović
Technical editor: Timothy Jaap van Deurzen
Production editor: Keri Hales
Copy editor: Lana Todorovic-Arndt
Proofreader: Melody Dolab
Typesetter and cover designer: Marija Tudor

ISBN: 9781633438330
dedication
To my husband, Steve Love, for supporting me and chatting about possible
examples and approaches used in this book when he wasn’t busy writing his
own.
contents
Front matter
foreword
preface
acknowledgments
about this book
about the author
about the cover illustration
1 Hello again, C++!
1.1 Why does C++ matter?
1.2 When should you use C++?
1.3 Why read this book?
1.4 How does this book teach C++?
Who this book is for
Hello, again, C++!
What you’ll learn from reading this book

1.5 Some pro tips


2 Containers, iterators, and ranges
2.1 Creating and displaying a vector
2.2 Creating and displaying Pascal’s triangle
A reminder of Pascal’s triangle
Coding Pascal’s triangle
Move semantics and perfect forwarding
Using ranges to display the vector
Using format to display output

2.3 Properties of the triangle


Checking the first and last elements of each row
Checking the number of elements in each row
Checking the sum of the elements in a row
How many rows can we generate correctly?
Checking whether each row is symmetric
Highlighting odd numbers in a row

3 Input of strings and numbers


3.1 Guessing a predetermined number
Accepting user input the hard way
Accepting optional numeric input
Validation and feedback using std::function and lambdas

3.2 Guessing a random number


Setting up a random number generator
Using the random number generator

3.3 Guessing a prime number


Checking whether the number is prime
Checking properties with static_assert
Generating a random prime number
Deciding which digits are correct
Providing different clues using std::function

4 Time points, duration, and literals


4.1 How long until the last day of the year?
4.2 Understanding durations in detail
Ratios
Durations
Literal suffixes and operator / for readable code
Requirements and concepts
How many days until the last day of the year?
Using last to find how long to payday
Writing testable code

4.3 Input, output, and formatting


Parsing a date
Formatting time points and durations

4.4 Time zones


5 Creating and using objects and arrays
5.1 Creating a deck of playing cards
Defining a card type using a scoped enum for the suit
Defining a card type using a strong type for the face value
Constructors and default values
Displaying playing cards
Using an array to make a deck of cards
Using generate to fill the array
Comparison operators and defaults

5.2 Higher-or-lower card game


Shuffling the deck
Building the game
Using std::variant to support cards or jokers
Building the game with an extended deck of cards

6 Smart pointers and polymorphism


6.1 A class hierarchy
An abstract base class
A concrete class
Warming up for a race
Using type traits to check for special member functions

6.2 Writing and using derived classes in a vector


A blob moving randomly
Smart pointers
Race!
Some design considerations

7 Associative containers and files


7.1 Hardcoded answer smash
Creating and using an std::map
Pairs, tuples, and structured bindings
A simple answer smash game

7.2 Associative containers


The map type in more detail
Using lower and upper bound to find a key more efficiently
Multimaps

7.3 File-based answer smash


Loading data from a file
Picking a word randomly using std::sample
Answer smash

8 Unordered maps and coroutines


8.1 Randomly generated matching pennies
8.2 Matching pennies using an unordered_map
Unordered containers and std::hash
Using an unordered_ map to make a prediction
The mind reader game

8.3 Coroutines
How to make a coroutine
A coroutine function
The coroutine’s return object
RAII and the rule of zero
Filling in the promise_type
Filling in the Task type
A coroutine mind reader

9 Parameter packs and std::visit


9.1 The triangle numbers
Testing our triangle numbers with algorithms
Execution policies for algorithms
Mutable lambdas
More properties of the triangle numbers

9.2 A simple slot machine


Revision of constexpr and std::format
Using std::rotate to spin the reels
The simple slot machine

9.3 A better slot machine


Parameter packs and fold expressions
Using a parameter pack to find frequencies
A fairer payout
Allowing holds, nudges, or spins
Spinning reels with std::visit and std::views::zip

appendix Further resources


index
Front matter

foreword
C++ is an ever-improving language used in almost every
corner of computing, from embedded systems, operating
systems, browsers, games, and trading systems to the ebook
reader you may be using to read this book. A new C++
standard comes out every three years, and compiler vendors
are quick to pick up on the latest features. I’ve been writing
C++ professionally for over 20 years in the seemingly
disparate games and finance industries. I have mostly
worried about the performance of my code, which led to me
creating Compiler Explorer, and not about every little change
to the language.

All the while, at the back of my mind, I was concerned I was


missing something. When I heard Fran was writing this book,
I was excited to have the opportunity to catch up on the
newer parts of the language I’d been ignoring for so long.

I first met Fran at the C++ on Sea conference. She was


running the lightning talks—each speaker gets 5 minutes to
present, one after another in rapid succession. As the
compère of the talks, Fran had to cover while one person got
up on stage and the previous left, and in doing so, she
invited the audience to play various guessing games, such
the higher-or-lower card game or smash quiz, getting us to
guess various conference speaker names mixed up with C++
keywords. Little did we know she was trying out some of the
games she uses as examples in this book!

In this book, Fran covers many of the latest C++ features,


including smart pointers, ranges, optional types, variant
types, improved string formatting, constexpr, concepts, and
coroutines. If any of those sound unfamiliar to you, then
you’re in for a treat. As I mentioned, I haven’t always kept
up to date with the newer features, and reading this book
was a fun way of picking them up. And I finally learned the
difference between aggregate initializers and initializer lists!

The continued evolution of the language means C++ today is


not the bug-prone tangle of memory leaks you might
remember from the 1990s and 2000s. Unfortunately, online
resources are slow to catch up and often show the old,
deprecated ways of doing things. This book clears up a lot of
misconceptions and will set you up on the right track.

The examples are playful and fun but show real-world


nontrivial code. Each section shows the journey of
development, iterating on the code as Fran introduces new
concepts one by one. I encourage you to play along and
compile and run the code as you read each section. At least
for me, learning by doing works better than just reading
alone, and by tinkering with the code, you can get a better
sense of how easy it is to make changes.

Along the way, there’s great general development advice on


the tradeoffs we all have to make when writing code. There
are tests that explore the edge cases and how to handle
them, and even examples of how to write code that won’t
compile if used incorrectly, with helpful error messages.

Each section has relevant links to online resources such as


blog posts, reference sites, and online tools (not just
Compiler Explorer) that can help you understand the matter
more deeply. The links complement the book perfectly, not
distracting from the flow of the examples but giving you an
opportunity to explore further if you’re so inclined.

Learn C++ by Example is a fun and pragmatic way to learn


the newest features of C++. If, like me, you’ve been
worrying you’re missing out, or if you’re returning to C++
after an absence, then let Fran take you on a journey of
what’s possible with modern C++ and learn how to code your
way out of a paper bag too!

—Matt Godbolt

preface
I first encountered C++ when asked to write a C++ parser to
emulate code for an embedded device on a PC back in the
1990s. I only knew C at the time, so this was a baptism by
fire. The C++ was predominantly C with classes, like many
early versions of C++ were. Over time, I learned more and
fell in love with the language. As a long-standing member of
ACCU (https://accu.org/), I volunteered to become editor of
its Overload magazine, which means I have to write an
editorial every other month, as well as encourage people to
write and collate feedback from the review team. Overload
has a mix of articles from newcomers and seasoned
professionals, covering C++ in depth, as well as broader
programming topics, so as the editor, I need to try to keep
up to date with everything. This is a challenge, and I still
have lots to learn.

I have used C++ for personal projects, and you can find
many of my talks on YouTube. I have also used C++
professionally, predominantly in investment banks and other
financial institutions. I know other languages too, and often
act as an intermediary between the quant teams writing C++
libraries and the frontend teams using them. I do understand
a lot of the under-the-hood mathematics that rocket
scientists use in their coding. To be honest, I’ve only worked
with two rocket scientists, but you can do clever things with
C++. The important part is understanding what you are
doing and knowing how to test your code.

C++ is an evolving language, so I will never be up to date


with all the changes. However, being aware of what I don’t
know means I can pick specific parts to practice. In this
book, I share various small projects designed to help you
learn a variety of newer C++ features. Over the years, I
have met many people who used to know C++ but stepped
away to use another language for a while, and they were
overwhelmed by the number of new features and approaches
when they considered picking up C++ again. It’s
disheartening to spend time learning something and then find
it difficult to reacquaint oneself. I want to encourage anyone
in such a situation to focus on key elements to get back up to
speed. I hope this book fills that need.
This book does not cover everything that has changed from
C++11 onward. As I wrote this book, C++23 was finalized,
so I have included a few of the newest features at the time of
writing. C++ will continue to change, but having a few small
projects to play with means you can use them for practice as
the language continues to evolve. For instance, this book
uses various containers, from std::vector to
std::unordered_ map, and more. The containers have
been a fundamental part of C++ for a long time, but recent
changes make them easier to use. This book uses a variety
of new features, without trying to be a reference book for the
whole language. The “About this book” section gives further
details.

acknowledgments
This book has been fun and challenging to write. I’ve learned
loads as I’ve tried to explain various aspects of C++. I
frequently asked others for help or ideas, while aiming to find
simple but correct ways to describe the language. Thanks to
everyone who argued with me to ensure I was correct.

I would like to thank Matt Godbolt for writing a foreword for


me. I’m delighted you enjoyed reading this book.

At Manning, I’d like to thank my development editor Doug


Rudder and my technical editor Tim van Deurzen for their
feedback, help, and encouragement while writing this book.
In addition, thanks to the entire staff who helped produce
this book.
I would also like to thank everyone who has taken the time
to give me feedback, in particular Howard Hinnant, Andreas
Fertig, Nina Ranns, Silas Brown, and Seb Rose, who all took
time out of their busy schedules to comment in detail on
various chapters, calling me out where I was unclear or
incorrect. I’m also grateful to ACCU and those in the general
email group who explained interesting edge cases I
discovered as I wrote. Any remaining mistakes are my own.

I thank everyone involved in C++, including Matt Godbolt for


his Compiler Explorer, Andreas Fertig for C++ Insights, and
all those who spend time and money on developing new
standards or engaging in various discussion groups.

Finally, thanks to all the reviewers: Amit Lamba, Arun Saha,


Aryan Maurya, Balbir Singh, Clifford Thurber, David Racey,
Frédéric Flayol, Jean-François Morin, Johannes Lochmann,
John Donoghue, Jonathan R. Choate, Jonathan Reeves,
Joseph Perenia, Juan José Durillo Barrionuevo, Keith Kim,
Kent Spillner, Matteo Battista, Mattia Antonino Di Gangi,
Maurizio Tomasi, Michael Kolesidis, Mitchell Fox, Partha
Pratim Mukherjee, Patrick Regan, Raushan Jha, Rich Yonts,
Samson Hailu, Satej Kumar Sahu, Srikar Vedantam, Sriram
Macharla, Timothy Moore, Vimal Upadhyay, and William
Walsh. Your suggestions helped make this a better book.

about this book


C++ has changed a lot over the last decade or so. Some
people who used to know the language well might now be
put off by how many new things they will have to learn. It
doesn’t have to be so hard. Getting up to speed now will
make it easier to keep track as C++ continues to change and
evolve. This book focuses on small projects using various
parts of C++, rather than an exposition of the entire
language. You will try out some ideas and learn language
features on the journey, rather than plow through each part
of the language’s syntax and standard libraries using one-line
examples. The first chapter is an introduction, and from
chapter 2 until the last chapter, you will create small projects
and games to help you learn. You might even have fun!

Who should read this book


If you have used C++ before but have failed to keep up with
recent changes, this book is for you. If you used to be an
expert, but your knowledge has gone hazy, and you want to
get back up to speed, this book will help you. If you have
never been an expert but have previously used some C++
and want to learn more, in particular newer approaches and
features, this book will also be valuable.

How this book is organized: A road map


This book has nine chapters. The first chapter provides an
introduction, and the remaining chapters focus on a puzzle or
game to code. In some cases, we make a simplified version
first before improving the game. In all cases, we focus on
one or more main features of C++ and learn a variety of
other ideas and approaches on the way:
Chapter 1 provides background on C++, showing why it
is relevant and useful and introducing some recent
changes.
Chapter 2 uses an std::vector to create Pascal’s
triangle. It also covers move semantics, using
std::format, ranges, and lambdas.
Chapter 3 uses random numbers to make a number-
guessing game. It also introduces std::optional,
std::function, and handling user input.
Chapter 4 uses time points and duration from
std::chrono to write a countdown. We also meet user
literals and learn about std::ratio.
Chapter 5 covers writing classes to build a deck of cards
and play the higher-or-lower card game. It also covers
scoped enums, std::array, the three-way comparison
operator, and std::variant.
Chapter 6 uses classes again to make some blobs race
out of a paper bag, this time revising inheritance and
detailing the new special member functions now available
in C++. In addition, it covers the rule of zero, type traits,
and smart pointers.
Chapter 7 uses std::map and std::multimap to build
a game of answer smash. These containers are not new,
but we see how to use std::pair and std::tuple
with structured bindings, allowing us to query the maps
neatly. Furthermore, we also read data from a file.
Chapter 8 uses the newer std::unordered_map and
describes std::hash to build a mind-reading machine,
or at least a program that guesses if you will pick heads
or tails based on previous outcomes. It also shows how
to turn the mind-reading machine into a coroutine.
Chapter 9 rounds things out by going into detail on
parameter packs and std::visit, showing us how to
make a slot machine game. The chapter encourages you
to practice more with various algorithms, std::format,
and lambdas.

Start by reading the first chapter, and then get your chosen
compiler ready. You can read the chapters in any order;
however, they build on each other to some extent, even
though each creates a self-contained project. When a feature
is used again, the first mention is signposted, so you can skip
back if you need to. Reading the chapters in order might be
easier, though, as you gradually add new approaches to your
repertoire. However you decide to read this book, do stop
and try out some code. Then play the games you created, or
play with the projects. Keep your brain in gear, ask
questions, experiment, and above all, have fun!

About the code


This book contains many examples of source code, both in
numbered listings and in line with normal text. In both cases,
the source code is formatted in a fixed-width font to separate
it from ordinary text. Sometimes, code is also in bold to
highlight code that has changed from previous steps in the
chapter, such as when a new feature adds to an existing line
of code.

In many cases, the original source code has been


reformatted; we’ve added line breaks and reworked
indentation to accommodate the available page space in the
book. Additionally, comments in the source code have often
been removed from the listings when the code is described in
the text. Code annotations accompany many of the listings,
highlighting important concepts.

This book has code in all nine chapters. The code is all in the
book but can be cloned from
https://github.com/doctorlove/BootstrapCpp.git. The first
chapter is a short main function used to discuss modern
approaches in C++, while the fun and games start from
chapter 2. You will need a compiler, and
https://isocpp.org/get-started provides links to several good
free ones. Some features, such as std::format, are not
supported on all compilers, but the book calls this out, and
the source code has comments showing what to do instead.

You can get executable snippets of code from the liveBook


(online) version of this book at
https://livebook.manning.com/book/learn-c-plus-plus-by-
example. The complete code for the examples in the book is
available for download from the Manning website at
https://www.manning.com/books/learn-c-plus-plus-by-
example.

liveBook discussion forum


Purchase of Learn C++ by Example includes free access to
liveBook, Manning’s online reading platform. Using liveBook’s
exclusive discussion features, you can attach comments to
the book globally or to specific sections or paragraphs. It’s a
snap to make notes for yourself, ask and answer technical
questions, and receive help from the author and other users.
To access the forum, go to
https://livebook.manning.com/book/learn-c-plus-plus-by-
example/discussion. You can also learn more about
Manning’s forums and the rules of conduct at
https://livebook.manning.com/discussion.

Manning’s commitment to our readers is to provide a venue


where a meaningful dialogue between individual readers and
between readers and the author can take place. It is not a
commitment to any specific amount of participation on the
part of the author, whose contribution to the forum remains
voluntary (and unpaid). We suggest you try asking the
author some challenging questions lest their interest stray!
The forum and the archives of previous discussions will be
accessible from the publisher’s website as long as the book is
in print.

Other resources
Each chapter mentions further resources, and these are
collated into an appendix at the end of this book, so you can
easily look back without having to keep notes.
about the author
Frances Buontempo has many years of C++ experience. She
has worked as a programmer at various companies, mostly in
London, with a focus on finance. She enjoys testing and
deleting code and tries to keep on learning. She has given
talks on C++ and more, which you can find on YouTube. She
is the editor of ACCU’s Overload magazine and will happily
consider articles from readers who want to share what they
learned from this book.

about the cover illustration


The figure on the cover of Learn C++ by Example is “Femme
de l’Isle de Lemnos,” or “Woman of Lemnos Island,” taken
from a collection by Jacques Grasset de Saint-Sauveur,
published in 1788. Each illustration is finely drawn and
colored by hand.

In those days, it was easy to identify where people lived and


what their trade or station in life was just by their dress.
Manning celebrates the inventiveness and initiative of the
computer business with book covers based on the rich
diversity of regional culture centuries ago, brought back to
life by pictures from collections such as this one.
1 Hello again, C++!

This chapter covers


Why C++ is relevant
When C++ is useful
What you need to know before reading this book
How this book will bootstrap your knowledge of C++
What you’ll learn in this book

C++ is an old but evolving language. In programming, you


can use it for almost anything and will find its application in
many places. In fact, C++’s inventor, Bjarne Stroustrup,
described it as the invisible foundation of everything.
Sometimes, C++ might be present deep inside a library of
another language because it can be used for performance-
critical paths. Furthermore, it can run in small, embedded
systems, or it can power video games. Even your browser
might be using the language. C++ is almost everywhere.

The language is compiled and targeted at specific


architectures such as a PC, mainframe, embedded devices,
bespoke hardware, or anything else you can think of. If you
need your code to run on different types of machines, you
need to recompile it. This has pros and cons. Different
configurations give you more to maintain, but compiling to a
specific architecture gets you down to the metal, allowing the
speed advantage. Whatever platform you target, you will
need a compiler. You will also need an editor or integrated
development environment (IDE) to write code in C++.

C++ stems from C, which has similar advantages but is a


lower-level language. If you recognize ++ as the increment
operator, you’ll realize that the language’s very name
suggests it is a successor to C. You can avoid the depths of
pointers and memory allocations with C++ by writing higher-
level code. You can equally drop down to C or even assembly
language in C++ code. Although C++ was never intended to
take over the world or even replace C, it does provide many
new ways to approach coding. For example, you can do a
surprising number of things at compile time, using type-safe
features rather than preprocessor macros often used in C.

This language underpins diverse technologies, including


compilers or interpreters for other languages, and even C++
compilers themselves. You can develop libraries for use in
other languages, write games, price financial instruments,
and do much more. If you ever typed make at a prompt, you
were probably using C++ without knowing it. C++ may
power your browser or e-reader if you are reading this book
in digital form, or it may have been used to write device
drivers for your machine.

This book will give you a firm grounding in a handful of C++


language and library features. Each chapter walks through a
small, self-contained project, focusing on one area. Along
with each chapter’s main feature, other parts of the language
will be covered. For example, if you fill a container, such as a
vector or an array, you may also want a way to display and
manipulate its contents. Thus, the next chapter focuses on
vectors but also introduces ranges and lambdas, as well as
using format to display output. By gradually building up
your repertoire, you will gain confidence, which will allow you
to rediscover the joy of C++. This book will focus on several
fundamental parts, showing you various ways in which the
language is easier now than it used to be. You will end up
with a firm grounding, ready to use and learn more C++.

1.1 Why does C++ matter?


C++ is designed by a committee. Some languages are
introduced and developed by a company or an individual.
C++ is not. Originally invented by Bjarne Stroustrup,
Working Group 21 (WG21) of the International Organization
for Standardization (ISO) is now responsible for its new
versions. You can find more details at https://isocpp.org/std.
There’s been a new ratified standard every three years since
2011, each adding new features and sometimes simplifying
ways of doing things. This means there is a lot to learn.
Some documentation and descriptions sound as if they were
written in legalese, which can be overwhelming. This book
will use a few precise definitions to help you get the hang of
parsing such explanations. Members of the committee make
suggestions, write papers to explain their ideas, and
demonstrate how to implement new features or small
improvements, which leads to innovations that influence
other programming languages too. For example, Java and C#
would not have generics if C++ hadn’t introduced templates.
Ideas do flow in both directions. C++ also takes on board
Random documents with unrelated
content Scribd suggests to you:
Korea and effect a revolution in the government. The guilt of Kim Ok
Kun's betrayal of his sovereign was the more heinous from his
having been confidential adviser to the Crown during all the
negotiations with foreigners, between whom and the king he was
the constant referee. He carried into exile the innermost royal
secrets. The king's resentment against Kim was naturally embittered
by his impotence to avenge the treachery to which he had been a
victim.
For the preservation of peace and of friendly relations an agreement
was entered into between the three Governments to the effect that
Kim should not be permitted to leave Japan for any other country
excepting China or the United States. On these conditions the
refugee became an embarrassment to the Government of Japan,
which felt bound to protect him against counterplots while
preventing him from carrying out his seditious designs. Nevertheless
Nemesis was on the track of the assassin, and the way in which the
quarry was hunted down by the avenger of blood affords a greater
insight into the nature of the tragedy than do any of the
contemporary comments. It also serves to illustrate certain points in
the Korean character which are decidedly not without interest to
students of current history.
A member of an important Korean family named Hong had been
implicated in Kim's conspiracy, and by Korean law his whole family
were held guilty of the treason. The king fully exonerated the head
of the family, being convinced that no blame attached to him
personally. Nevertheless, the old man was so dejected by the
disgrace brought on his name, that he forthwith poisoned himself
with his whole house. A young man distantly connected with the
family of Hong, and bearing their surname, took upon himself the
duty of avenging these deaths, and set to work in a systematic
manner to compass the murder of Kim. The private vengeance of
Hong-tjyong-on fitted in well with his patriotic duty, and his scheme
was favoured by the Korean king. About three years after Kim's
flight, Hong made his way to Japan, bearing secret letters from the
king outlawing Kim and his followers and authorising their capture or
assassination. Hong's plan was to ingratiate himself with Kim as a
supporter of his schemes, but his recent arrival direct from Korea
without any credentials from the revolutionary party in that country
rendered Kim suspicious of the would-be recruit. Unable to gain the
access which he required to the person of his victim, Hong saw that
he would have to adopt more elaborate means to effect his purpose.
He went therefore to Europe, where he must have spent five or six
years at least in acquiring a European education, European manners,
and a perfect knowledge of European ways. He was courteous,
refined, and intelligent, a great favourite in society (especially in
religious circles), and made in particular many warm friends in
France. Having thoroughly shaken off Korea, he thought he might
now present himself in Japan in a character that would disarm all
suspicion. Accordingly he made his way thither, and succeeded in
attaching himself to Kim, talked progress and revolution, and
thereby insinuated himself into the confidence of the arch-
conspirator, becoming gradually master of his secret plots and
schemes. The arrangements of the Japanese Government for the
protection of Kim's person seem to have been so efficient that, in
order to accomplish his purpose, Hong perceived that it was
necessary to induce Kim to leave Japan. This seemed the most
difficult part of his enterprise, and a far-fetched scheme had to be
contrived in order to furnish Kim with a plausible reason for
proceeding to China. Between the plots which Kim may have had in
his mind and those which Hong for his own purposes suggested to
him, it is not possible, neither is it necessary, to distinguish. Hong's
own account of the matter was, that Kim had been concerting some
movement on Korea from a Russian base, but was prevented from
proceeding to Vladivostock by the vigilance of the Japanese
Government. The agreement between the three Powers would not,
however, be violated by his proceeding to Shanghai, where he would
find the means of continuing his voyage to Vladivostock, for neither
of the travellers apprehended any difficulty in eluding the
surveillance of the Chinese officials and taking passage in a trading
steamer to the Russian port.
Kim eventually fell in with this proposal, and left Japan with a
Japanese servant, accompanied by Hong. They arrived in Shanghai
on the 27th of March 1894, repaired to a Japanese hotel, and
reported themselves at the Japanese consulate. The following day
Hong, having first put on Korean upper garments, murdered Kim,
and fled, but was captured at Wusung by the foreign municipal
police of Shanghai, and by them detained in custody until claimed by
the Chinese authorities under instructions from Li Hung-chang. The
news of the assassination was received by the Chinese Government
with a sense of relief and "sombre acquiescence," but at the Korean
Court with almost a frenzy of delight. The king gave a banquet in
honour of the event, to which he invited all the foreign Ministers.
The Chinese Government ordered a man-of-war to convey the
murderer and the remains of the victim to Korea. The former was
covered with honours, while the remains of Kim were treated with
savage indecency and his family put to death.
Thus did the assassin of 1884 expiate his crime exactly ten years
later.
The issue of the plot of 1884 was not agreeable to the Japanese,
who were particularly affronted by the fact that the Chinese were in
a position to snatch the king out of their hands and to afford him
military protection against all comers. But Japan was in no humour
to relinquish her own policy in Korea, which was quite incompatible
with the suzerain status of China, and with the very concrete form in
which it had just been manifested. One of the leading statesmen of
Japan, Count Inouye, was sent to Korea to investigate the whole
affair, and inquire into the relative position of China and Japan in the
peninsula. The result of his inquiries was a determination to follow
up by orthodox diplomacy the disintegrating effects which the risings
in 1882 and 1884 had no doubt been intended to subserve. China
being in the throes of a war with France, the moment was
particularly favourable for preferring demands upon her. An embassy
was therefore despatched to Peking, under Count Ito, in March
1885. He counted much on the friendly offices of the British Minister,
Sir Harry Parkes, in smoothing the way to amicable negotiations with
China, but unhappily the Japanese ambassador arrived at Peking
almost on the day of Sir Harry's death. After vain attempts to deal
with the Tsungli-Yamên the Japanese mission withdrew to Tientsin,
where negotiations were entered into by Li Hung-chang, extending
over several weeks. Count Ito's mission was successful in concluding
a treaty by which China and Japan were put on a footing of equality
in the peninsula so far as regards military protection. The troops of
both countries were to be withdrawn, and neither party was to send
a force in future without giving written notice to the other. This
arrangement was a surrender in substance of China's suzerainty over
Korea, though she retained the ceremonial form in full vigour for
nine years after.

III. THE PORT HAMILTON EPISODE, 1885-1887.

Sudden occupation of Korean harbour by Great Britain—Questioned by China,


Japan, and Korea—Position condemned by naval authority—Abandoned on
guarantee from China against occupation by other Powers.

"In view of potentialities" the British Government on April 14, 1885,


sent instructions to Vice-Admiral Dowell to occupy Port Hamilton, an
island harbour on the coast of Korea. This high-handed proceeding
was justified on the plea of necessity—the necessity, as explained by
Lord Granville, of anticipating the "probable occupation of the island
by another Power." Naturally the measure disturbed neighbouring
States, as well as the Government of Korea itself. China and Japan
asked for explanations, and an agreement with the former, as
suzerain of Korea, was about to be signed for the temporary use of
the harbour by Great Britain, when the Russian Minister at Peking
interposed with an intimation that if China consented to the
occupation of Port Hamilton by Great Britain, Russia would
compensate herself by the seizure of some other point of the Korean
littoral. The protest of the Korean Government thus became merged
in negotiations with China, but was never withdrawn.
While these pour-parlers were going on, the position of Port
Hamilton was unequivocally condemned as a naval station by a
succession of three admirals commanding the China Squadron; and
as the immediate occasion of the occupation of the harbour had
happily passed, there remained no ostensible reason for prolonging
it. Before abandoning the island, however, the British Government
hoped that some arrangement might be come to for an international
guarantee of the integrity of Korea, which being already a bone of
contention between certain Powers, and unable to defend its own
independence, constituted a constant menace to the peace of the
Far East. The proposal met with no favour from the Chinese
Government, for the reason probably that it would have involved an
organic change in its own relations with Korea. The next proposal
came from the Korean Government itself, which suggested a modus
vivendi by opening as treaty ports both Port Hamilton and Port
Lazareff, which latter was the point Russia would have seized if she
had seized anything. This idea was approved of by the British
Government, but nothing came of it. Eventually the evacuation was
agreed to on the assurance from China that neither Port Hamilton
nor any other portion of Korean territory would in future be occupied
by any other Power. This pledge China was enabled to give on the
strength of an equivalent guarantee which she had received from
Russia, that Power being then the only one considered as likely to
cherish aggressive designs on the Korean peninsula. These
engagements were exchanged in November 1886, eighteen months
after the occupation, and the British flag was finally hauled down on
the island on February 27, 1887.
The net visible result of the incident was to confirm China in her
suzerainty, since the negotiations were made with her and not with
Korea, and to obtain a specific pledge from Russia that she would
keep her hands off Korea "under any circumstances." It was argued
seven years afterwards that Russia had broken her pledge by her
interferences in Korean affairs, but in 1895 a new state of
circumstances had been brought about. China in that year ceased to
be the suzerain of Korea, and obligations which were valid under the
old régime necessarily lapsed. A new page of history was turned,
and Korea attained the status of a nominally independent kingdom.

IV. TIBET.

Lhassa visited by Babu Sarat Chandra Das—Proposed commercial expedition—


Originated by Secretary of State—Envoy sent to Peking to obtain passport—
Opposition organised by Chinese and Tibetans—Mission withdrawn.

The year 1885 witnessed the first act in the ill-advised policy—as to
its method, not its object—of the Indian Government of opening
commercial relations with Tibet. A learned Bengali pandit, versed in
Tibetan, had made two successful visits to Lhassa, where he gained
the friendship of the lamas, who invited him to come again. A fair
prospect of opening commercial relations by gradually disarming
prejudices and apprehension was thus presented. Having duly
reported his experiences to the Government of India, the babu
waited their pleasure as to further developments at Darjeeling,
where he occupied the post of Government schoolmaster. An English
civilian, making the acquaintance of the babu in that hot-weather
retreat, conceived the idea of an official mission to Lhassa, in which
the services of the babu might be utilised as guide and interpreter.
The Indian Government was averse from the enterprise on
economical if on no other grounds, but direct pressure being brought
to bear on the India Office in London, the ambitious young
statesman who then presided over its counsels is said to have
espoused the proposal and overruled the reluctant Government of
India.
Of the organisation and procedure of the mission nothing very
complimentary can be said. Instead of following the line of least
resistance, of driving in the thin end of the wedge, in accordance
with the commonplace maxims consecrated by all human
experience, the reverse process was followed in every single
particular. Sarat Chandra Das had shown the way, and the entry he
had effected could have been gradually widened by himself and
others of his own class until the obstacles to free commercial
intercourse had been overcome. The experience of a hundred years
had shown to the world the invincible prejudices of the Tibetan
rulers against foreign visitors. The babu had in his own person
conquered these prejudices by his mastery of Buddhistic lore, as well
as by his gentleness and consummate tact; but the mission, which
had its origin in the information he supplied, discarded his methods
and proceeded on military lines. Its personnel included politicals and
scientists, but no commercial agent, and as Mr Gundry has well said,
"The Under Secretary of State, while stating that the object of the
mission was to confer with the Chinese commissioners and the
Lhassa Government as to the resumption of commercial relations
between India and Tibet," added in Parliament that, "looking to the
delicate nature of the mission, it had not been thought advisable to
appoint a special commercial representative." An armed force of
some 300 men sent on a "delicate mission" which, though essentially
commercial, yet had nothing commercial in its composition! Could
anything be conceived more certain to arouse the sleeping
suspicions of the Tibetans? It was but repeating on a larger scale the
deplorable fiasco of Colonel Browne's attempted march from Burma
to China in 1875.
The first act in this little drama was performed in Peking when the
envoy, Macaulay, arrived with his staff for the ostensible purpose of
applying for a passport for Tibet. For such a purpose there was no
need to have sent a special messenger to Peking at all, as a passport
could have been much more easily obtained by the British Minister
there and transmitted by post in the ordinary course of business.
The passport could not, of course, be refused in plain terms by the
Chinese Government, but the personal demand for it gave them the
opportunity of cross-examining the intended envoy as to the objects
of his proposed mission. It may well be believed, from the self-
contradictory explanation of the mission tendered to the British
Parliament, that the envoy in Peking failed to allay the suspicions of
the Chinese Government. On the contrary, his presence intensified
them exceedingly. The sole effect of the preliminary expedition to
Peking was, in fact, to forewarn the Chinese Government, so that
they, in concert with the rulers of Tibet, should be prepared to
interpose obstacles to the advance of the mission, but in such a way
as not openly to compromise the good faith of the Chinese
Government. The journey of the envoy to Peking, therefore, sealed
the fate of his own mission, and at the same time closed Tibet
against more judicious advances in the future.
The most interesting episode in connection with this abortive effort
was the appearance of the Babu Sarat Chandra Das himself in the
Chinese capital. By sheer force of intellect he succeeded in a few
days in obtaining the confidence of the inner circle of the lamas
there. Having been brought in contact with a certain Manchu official,
the pandit showed very unobtrusively a familiarity with the more
recondite tenets of Buddhism which captivated the Manchu, whose
heart was set on improving his knowledge of the sacred mysteries.
[24] The babu could speak no Chinese, but it was not difficult among
the thousands of lamas in Peking to find a competent Tibetan
interpreter. The fame of the pandit spread rapidly among the ranks
of the priesthood, whose chiefs competed for the honour of sitting at
the feet of the Indian Gamaliel. In expounding the doctrines, while
enjoying the hospitality, of different groups of lamas, the popularity
of the pandit grew from day to day, until he was at length
constrained to take up his quarters at the great Yellow Temple,
outside the north wall of Peking, and live with the brethren. They
invested him with the yellow robe and the other ecclesiastical
insignia, and treated him altogether as one of the initiated. It
required all his acumen to prevent his status as a Buddhist lama
from clashing with his position as a subordinate of the Indian envoy,
on whom he was in attendance. He had to pay frequent visits to the
British Legation, where it would have been impossible for him to
appear in his religious vestments without exciting inconvenient
gossip, and perhaps incurring the disapproval of his superior officer.
The custom of travelling in Peking in closed carts enabled the babu
to play the double part of Jekyll and Hyde with perfect success. He
would leave the Temple as a lama, drive to a friend's rooms in the
city, where his Indian costume was kept ready, in which he
proceeded in another cab and in another character to the British
Legation, returning to reassume his yellow robes and then repair to
the Temple.
During the time when the envoy designate remained in Peking a
very high personage arrived from Tibet, and it was on his
conferences with the Chinese Court that the success of the intended
mission depended. It would be presumptuous on the part of any
foreigner to attempt to divine what passed between the delegate
from the Grand Lama and the Chinese Ministers; but were it possible
for any one to penetrate into those secret counsels, the babu was
the man to do it. There is no doubt that he did. In fact, he had
positive information that the Indian mission to Tibet would be
stopped at the instance of the Chinese Government, and that the
issue of the passport was an empty form. Such information would
naturally be unwelcome to the envoy, and the sequel seems to show
that the warning was disregarded. The expedition was organised,
fully equipped, ready for a march into Tibet. Had it proceeded it is
highly improbable that the babu would have accompanied it as
interpreter, for he could not have exonerated himself from the
imputation of bad faith towards his Tibetan hosts in acting as guide
to an armed force into a country where he had been received and
reinvited as a private guest.
What would have been the consequence of the mission proceeding
into Tibet it is, of course, impossible to say, but the circumstances of
its recall were not conducive to satisfactory relations between China
and Great Britain. Mistrusting the effectiveness of the Tibetan
opposition to the Indian mission—for the force could very likely have
made good its passage to Lhassa—the Chinese Government resorted
to diplomatic means of stopping its advance. Its never-failing
emergency man, the Inspector-General of Customs, was called
upon, and he intervened with the British Government with such good
effect that they sent orders to India to stop the Tibetan mission.
Thus the Indian Government was a second time overruled: first, in
being made to organise the mission against its will; and secondly, in
being forced to recall it when its recall involved immeasurable loss of
influence in future dealings with China. An attempt was made to
cover the retreat in a cloud of verbiage by a convention signed at
Peking in 1886, which, however, only made the case worse, in that it
was a retrograde step, virtually cancelling the right of visiting Tibet,
which had been conferred by the Chefoo convention of ten years
before. The same treaty which embodied this renunciation, perhaps
the weakest to which any British representative ever set his name,
also fostered the illusions which have been so detrimental to the
welfare of China, by promising a continuance of the tribute missions
from Burma after that country had become an integral part of the
Indian Empire.
The fruits of this diplomatic surrender were not long in showing
themselves, for it was soon followed by an invasion of British Sikkim
from the Tibetan side. This aggression of the lamas was of necessity
resisted by the Indian Government, and an unexpected opportunity
was thus offered to them of settling the whole Tibetan question by
the rapid march of a small force to Lhassa. There is good reason to
believe that this solution of the difficulty was the one which
commended itself to the practical statesmen and soldiers of India;
but their action was paralysed by the orders of the Home
Government, which continued to be ruled by influences which were
neither military nor political nor practical. Discussions between the
Indian Government and the Chinese amban or Resident at Lhassa,
professing to speak for the Tibetan Lama Government, were
protracted year after year, and seemed interminable. At last even the
Chinese themselves grew weary of the comedy, and experienced in
Tibet something of the difficulty which occasionally beset them in
China—that is to say, they were unable to exorcise the demon they
had invoked. They had stirred up the Tibetans to the point of
obstructing the Macaulay mission, but seemed really to lose control
of the force after it had been set in motion. After some years of
futile talk the statesmen of China would perhaps have hailed with
satisfaction the advance of a British force to Lhassa to cut the
Gordian knot; but they dared not, of course, give such a hint as was
conveyed to Captain Fournier, "Avancez donc,"[25] and the Indian
Government, not having the wit to divine it, had to submit to a long-
drawn-out and permanent humiliation, that was in no wise mended
by the Calcutta convention of 1890, which, professing only to settle
the existing frontiers, did not even settle them.

V. THE CRUISE OF THE SEVENTH PRINCE, 1886.

Character and position of Prince Ch'un—Had been misunderstood by foreigners


while he was in seclusion—An amiable and progressive man—His visit to Port
Arthur in 1886—Intercourse with many foreigners.

The spring of 1884 witnessed a ministerial crisis of the first order in


Peking. For twenty-four years Prince Kung, uncle to the deceased
emperor Tungchih, had held a position equivalent to Chancellor of
the empire. To the outside world he was only known as Minister for
Foreign Affairs and head of the Tsungli-Yamên. During the greater
part of the time he had been at feud with the empress-regent, from
whom his power was derived, but, being indispensable to her, he
was tolerated for want of a competent successor. The troubles in
Tongking caused an agitation in the capital, and the empress seized
the opportunity to dismiss Prince Kung with most of his colleagues of
the Yamên and introduce a fresh set. The eminent position of the
prince, however, was one difficult to fill; but the substitution was
effected by a kind of coup d'état by which the empress brought the
younger brother of Prince Kung out of his retirement and made him
virtually, as far as it was possible, her coadjutor in the Government.
But the peculiar status of Prince Ch'un, as father to the reigning
emperor, rendered him immune from responsibility, since in China
the son could not place the father under discipline. For this reason
the prince could not in his own name exercise any of the great
functions of the State. He was therefore obliged to keep in the
background, while the executive service was performed by his
nominees. Thus in foreign affairs he was efficiently represented by
the Grand Secretary Li Hung-chang, and by Prince Ch'ing, a junior
member of the imperial family, who was made president of the
Tsungli-Yamên, and holds the office to the present day.
Whatever the true motives may have been for recasting the Tsungli-
Yamên—and it would be hazardous for any foreigner to dogmatise
about such matters—a great improvement was remarked in the
efficiency of that body. Prince Ch'ing, though new to public affairs,
acquitted himself like a gentleman, and gained the goodwill of all the
foreign Legations by his laborious efforts to learn his work and to
bring justice and reason as well as courtesy into the transaction of
business. The circumstances of the time were also favourable to
improvement; for being at war with one great Power, China was
naturally most anxious to conciliate the others. While this amenable
temper lasted, business was despatched by the Tsungli-Yamên with
a celerity never before known, and good use was made of the
opportunity to clear off legacies of arrears that had been
accumulating in the foreign legations.
The Seventh Prince, so long as he was in seclusion, had stood in the
opinion of foreigners for everything that was fanatical, obstructive,
and irreconcilable, the head of the war party, and so forth. Even Sir
Rutherford Alcock, in an article on Chinese Statesmen in 1871,
adopted this popular estimate, calling him "violently hostile, joining
with Wo in all efforts to make the anti-foreign faction predominate."
The announcement of Prince Ch'un, therefore, as the successor of
Prince Kung not unnaturally aroused apprehension of a reactionary
policy. His first public act, however, in so far as it was his, dispelled
the misconception under which foreigners had been labouring for
many years: it was to conclude a peace with France in the face of a
rabid opposition. This misconception of Prince Ch'un's character and
policy is only an example of how vain it is for foreigners to attempt
to sound the currents of Chinese politics, more especially where
palace factions are concerned.
The advent of the Seventh Prince having removed all friction
between the empress-regent and the Government, it was a signal for
tentative reforms and what foreigners call progress. Li Hung-chang
had to a considerable extent imbued the Court with his own ideas.
He assured them there was no danger in adopting foreign methods
and foreign manners,—on the contrary, that to do so was the only
means of safety to the empire. Within a few months of his taking the
reins, the Prince established a precedent which amounted to a small
revolution in its way. He began to transact business through his
agents with foreigners in the capital itself, which had been up to that
time strictly preserved from all contamination of foreign trade. The
two "stores" which existed were not traders by right, but were under
the special protection of certain foreign Ministers, who had
represented to the Government the necessity of such agencies for
the supply of necessaries for the use of their Legations. This was
followed in course of time by the introduction of novelties in the
palace, such as electric light, toy railways and steam launches in the
imperial pleasure-grounds. The telegraph wire itself was introduced
into the city during the summer of 1884, it having been previously
jealously kept at a distance of thirteen miles, from superstitious fears
concerning the sinister influence which the electric wire might exert
over the fortunes of the capital. However real such fears may be in
the minds of the Chinese, and however convenient they may be as a
defence against proposals from without, they invariably yield to the
pressure of necessity. While the terminus of the telegraph line was
at Tungchow, the inconvenience of having to send mounted
messengers thirteen miles to despatch and receive messages was
for some time felt almost entirely by the foreign Legations; but when
the war crisis with France arose, and the Chinese Government itself
was sending urgent messages requiring immediate answers to the
southern provinces and to Europe, the absurdity of losing more time
between the Tsungli-Yamên and the telegraph station than was
occupied by the transmission of the message and its reply from
Europe became so striking, that the order was given to bring the
telegraph into the city. No more was heard of geomantic difficulties.
The most important object, however, which Li Hung-chang sought to
gain through the activity of the Seventh Prince, was so to interest his
Highness in the scheme of national defence, which had been
growing under the viceroy's initiative, that this department of the
work of Government should be transformed from a provincial to an
imperial concern. With this end in view an expedition on salt water
was arranged for the Prince; and insignificant as the feat must
appear in Western eyes, yet for a Manchu prince, who had never
seen the sea, to be allowed to trust himself on the treacherous
element at all, or on such a strange monster as a steamer, must be
accepted as a decided proof that the old order was changing, giving
place to the new. The prince was undoubtedly nervous, not knowing
what should befall him on his expedition.
The first ordeal through which he had to pass was that of personal
contact with foreigners, of whom he had perhaps never seen one in
Peking. His introduction was carefully organised by Li Hung-chang,
and it was at Tientsin that the prince first met with foreign officials,
who waited upon him at separate audiences. The foreigners were as
much charmed with his Highness as he expressed himself to have
been with them, so that he embarked on his cruise free from
anxiety. His attendants, however,—on whom and on Li Hung-chang
all the responsibility of course rested,—continued to feel anxious
during their passage across the Gulf. This feeling became for a
moment acute when, on landing at Port Arthur, they were met by a
British admiral and staff with a guard of honour. It is an actual fact
that the sight of strange armed men waiting for the prince, working
on oriental traditions, did suggest a trap, for the idea of capture by
treachery is never wholly absent from the Chinese mind. The
Government had taken the wise precaution of attaching to the prince
an experienced and capable foreigner in whom he reposed perfect
confidence, and Mr Detring explained foreign customs and forms of
courtesy to the prince and his suite in a way which completely
reassured them. Among all the dignitaries in the prince's suite,
however, there was not one capable of taking in the entirely novel
ideas which were presented to them. One man only, of quite
subordinate rank—whether a Manchu or a Chinese by birth is
unknown to the writer—a confidential agent of the Seventh Prince in
business matters, seized the entire programme of foreign etiquette
the moment it was explained to him, and through him the whole
ceremony passed smoothly and agreeably to all parties. The name of
this official was Chang Yi, who has since been taking a leading part
in mining, railway, and other progressive enterprises in China.
On his return to Peking Prince Ch'un in a memorial to the Throne
reported fully the incidents of his cruise to the gulf ports. Not long
after a naval board was established in Peking, with the prince at its
head. As a step in the direction of centralising the naval authority,
which included also the direction of the land defences, the
establishment of a Board of Admiralty in the capital was certainly a
progressive one; but as its members possessed neither knowledge
nor experience of naval or military affairs its authority was much
attenuated, almost every question having to be referred back to Li
Hung-chang in Tientsin. Any chance that might have existed of
Prince Ch'un himself inspiring the new Board and bringing it up to a
state of efficiency was lost through his Highness falling into ill-
health, from which he never recovered, but after a lingering illness
died in 1890.

VI. THE EMPEROR ASSUMES THE GOVERNMENT, 1889.

The Emperor Kwanghsu comes of age in 1889—Audience of foreign Ministers


arranged—Derogatory conditions—Second audience refused by Ministers—
Accepted by Austrian and British envoys.
In 1889 his Majesty Kwanghsu attained his majority and married.
But his coming of age was a somewhat gradual process, with
intervals between each step, as if the empress-regent, who alone
determined the time and the seasons, were either mistrustful of the
capacity of her nephew or reluctant to lay down the reins of
authority. The emperor, kept in leading-strings, was allowed to
assume some of the functions of an autocrat, but not all. This slow
unfolding of the imperial blossom had this result among others, that
it procured a welcome respite from the bitter ordeal of granting an
audience to the representatives of foreign States. It was well
understood that the foreigners had for sixteen years been looking
forward to the emperor's assumption of power as to the
consummation of their diplomatic function, and that as soon as a
decent interval had been allowed to the young monarch after his
majority, the subject would become pressing.
It had been discussed in whispers for nearly two years, when, to the
astonishment of everybody, including even the members of the
Tsungli-Yamên themselves, an imperial decree was issued in
December 1890 in kindly terms ordering preparations to be made to
receive the foreign Ministers after the Chinese New Year—that is, in
the February following. Since nobody owned to having been in the
secret, the act was set down to the emperor's gracious initiative, and
was hailed with enthusiasm as the opening of a new era. The Great
Wall had at last fallen; the pretensions to superiority for which the
Chinese had made such great sacrifices were suddenly abandoned,
and henceforth equality with foreign nations was to be the basis of
their diplomatic intercourse.
The hope was shortlived, for as soon as the details of the imperial
reception came to be arranged with the Tsungli-Yamên all the old
difficulties appeared in an aggravated form. The foreign ministers,
having pondered the question for eighteen years, had unanimously
resolved that they would not accept an audience in the building used
for the reception of tributary princes, where the ceremony of 1873
had taken place, but only in the imperial palace, or not at all. The
whole value of the audience was the acknowledgment it signified of
international equality. The idea that it would facilitate business must
have been long before abandoned. The form, therefore, was
everything, and the Chinese Ministers were resolved that the
"tributary" form should be adhered to. They became urgent in their
appeals to the reasonableness of the foreign Ministers. They had
gone to expense in renovating the hall, Tz-kwang-ko; they had no
other place available; the imperial decree must be obeyed, and this
admitted of no postponement.
Yielding to these arguments, the foreign Ministers agreed to a
compromise. They would, for this time only, repair to the Tz-kwang-
ko, but never again. The ceremony took place therefore on 5th
March 1891. There were two receptions—first an audience to the
various foreign Ministers separately, next a general reception of the
whole of them. The diplomatic body soon felt the consequences of
their retrograde step, for when they came to discuss details of the
audience of the following year, the Chinese interposed a simple non
possumus to every demand which implied the acknowledgment of
equality. A reception within the palace without the kotow could not
even be discussed. No accommodation between the opposing views
being possible, there was no audience in 1892. The diplomatic body
were solidly united in maintaining the dignity of their respective
countries, and by ceasing to solicit, they left the onus of discovering
a solution of the question on the Chinese themselves. The audience
was of no practical value to the foreigners, while the withholding of
it placed the Chinese so much in the wrong that they might safely
have been left to their own devices.
Before, however, the pressure to extricate themselves and their
sovereign from an untenable position had become too severe, a
diversion in their favour was created by the flying visit of an Austrian
envoy, who seemed ready to present his credentials on any terms
whatever, so that the formalities were quickly got over, and he
enabled to conclude his mission. The Chinese availed themselves of
this unexpected opportunity, and the emperor granted an audience
to M. Biegeleben in another hall or pavilion outside the palace, which
thenceforth became known locally as the Palais Biegeleben.
At the end of 1892, not long after the Biegeleben incident, a new
British Minister arrived in Peking. Not apparently considering himself
bound by the compact to which his predecessor was a party, he,
without the knowledge of his diplomatic colleagues, accepted an
audience on the same derogatory terms as the Austrian envoy had
done, and the reactionary policy of the Chinese thus enjoyed a
complete, if temporary, triumph. This proceeding of the British
Minister was deeply resented by the diplomatic body, most of all by
the Russian Minister, Count Cassini, himself a new arrival, and the
circumstance did not tend to smooth the subsequent intercourse
between the parties.

VII. THE VISIT OF THE CZAREVITCH, 1891.


Worthy reception in Peking impossible—Attempted substitution of provincial
reception—Czarevitch visits only the Russian communities in China.

Closely connected in point of time, and possibly by a more vital link,


with the imperial audience was the voyage of the Czarevitch to
India, China, and Japan in 1890-91. There was no precedent in
China for the reception of the member of any foreign royal family. In
the days before the first audience the Duke of Edinburgh, while in
command of the Galatea, visited Peking, but strictly incognito, no
visits being exchanged with any Chinese. But times had changed
considerably in the twenty years that had since elapsed, and with an
emperor of full age on the throne things that were winked at during
his minority could no longer be so lightly treated. The Chinese
Government were, in fact, perfectly conscious of the responsibility
which lay upon them to show courtesy to so distinguished a visitor
as the heir to the throne of Russia, and they took timely measures
for his reception.
The position of the audience question convinced the Ministers that it
would be impossible to receive him worthily in Peking, since to do so
would be to admit equality with foreign States. The first care of the
Chinese, therefore, was to induce his Imperial Highness to stay away
from the capital. The Russian Government were told that Li Hung-
chang, representing the Chinese Emperor, would meet the
Czarevitch at Chefoo, and that his reception by other Governors of
provinces would be deemed equivalent to one by the emperor in
person. The Russian Government fell into the trap, and the
programme of provincial receptions would have been carried out but
for the eccentricity of Chang Chih-tung, the governor-general of the
Hu provinces on the Yangtze. He, with the other provincials, had
received the instructions about the reception of the Czarevitch, but
he alone treated the order with contempt, not even deigning to
answer it or to explain his reason. The order did not emanate from
Peking, and he would not accept a mandate from an equal. Evidently
the emperor had no hand in drawing up the programme, and this
Chang had the best means of knowing, for he had a brother in the
Inner Council. This action of a high authority throws full light on the
difference between an imperial and a provincial transaction, as the
Chinese themselves regard it.
In keeping with this independent attitude of Chang was the rudeness
with which he received the officer deputed by the Russian admiral to
arrange details of the reception at Wuchang. In this way the
intended imposture was exposed. But if the Russian Government
had been too easily led into a false position, it must be admitted
they extricated themselves cleverly, by simply demanding a yellow
chair for the Czarevitch, a colour reserved exclusively for the
emperor. As this could not be conceded the official ceremonies fell
through, and the Czarevitch contented himself with visiting the
Russian communities at the Chinese ports. He then proceeded to
Japan, where a brilliant reception awaited him; and from Japan to
Vladivostock, where he turned the first sod of the Trans-Siberian
Railway, 19th May 1891.
CHAPTER XXVI.

THE TONGKING QUARREL.

Rapid advance of French towards China proper—The Black Flags—Discussions


between France and China—Attempted negotiations—Conquest of Tongking
decided upon—Chinese feared attack on Canton—City defenceless—Negotiation
with France recommended—Captain Fournier concludes convention with Li
Hung-chang in Tientsin—Strong opposition in the capital—Collision between
forces in Tongking—French make war on China—Peace concluded through
customs agency, April 1885—The Li-Fournier convention ratified.

The progress of the French in the annexation of Cochin China,


Annam, and Tongking was phenomenally rapid. These aggressions
on her tributary States were far from agreeable to China, but no
effective means of resistance was proposed. The Chinese policy,
wrote Sir R. Alcock,[26] "has been one of drift, and letting things
slide into irretrievable confusion and disaster for want of courage
and decisive action at the right time. Between the Dupuis and
Garnier expeditions, in which a handful of men were seizing towns,
storming citadels, and terrorising the Annamite mandarins and king
into virtual submission to any terms dictated to them, and Captain
Rivière's very similar proceedings in 1883, there was abundant time
and opportunity for China either to fight or to negotiate with effect,
but she did neither."
When, however, the advance of the French brought them within
measurable distance of the southern provinces of China proper, a
more serious view of the invasion was forced upon the Government.
A body of irregular troops, called the Black Flags, for some time
stood in the way of the French, who designated them "pirates." The
status of these Black Flags was, indeed, somewhat ambiguous, as
they had been virtually outlawed by the Chinese. But when it was
seen that they were harassing the French, the provincial authorities
recognised that they were fighting the battle of China and of her
tributary. The Annamese Government had, in the first instance,
invited the assistance of the Black Flags, and the Chinese
Government officially encouraged them, while hoping to evade direct
responsibility for doing so. The French had made the useless mistake
of wounding China in a tender spot by destroying the seal granted to
the Annamese sovereign by the emperor, and it was probably this
insult rather than the territorial seizures which induced China to
reinforce the Black Flags by a body of imperial troops, and to lay
down distinctly the line which she would consider herself bound to
defend.
The annexation of Annam became the subject of protracted
discussions between France and China. The diplomacy of the
Marquis Tsêng in Paris, and of Li Hung-chang in China—a convention
had actually been concluded between the latter and the French
Minister, Bourrée—failed to arrest the progress of France, and the
question between the two countries reached a burning point after
the capture by the French of Sontay and Bacninh in the spring of
1884.
The Chinese envoy had declared to M. Ferry that a French advance
on these places would be regarded by his Government as a casus
belli. Seeing, however, that no action was taken by China after their
actual capture, the French took fresh courage, and their programme
of conquest became so much expanded that what had been the
dream of a few became the definitive policy of the Republic. "The
conquest of Tongking had been decided upon in principle," wrote
Admiral Jaurèguiberry to Captain Rivière at the time when M. de
Freycinet was declaring that there should be no policy of aggression.
The taking of the two citadels sealed the policy of the admiral and
falsified that of the Foreign Minister. From that point may be dated
the important position which France has since assumed in claiming
to direct, in conjunction with Russia, the destinies of the Chinese
Empire.
On the fall of the two cities the Chinese officials of the southern
provinces were filled with consternation. They feared that the
successes of the French would encourage them, if not to invade
China, at least to force a settlement with her on their own terms.
They had before them the brochure of Captain Rivière, commander
of the French forces in Tongking, in which he advocated a quarrel
with China as a preliminary to the seizure of the three southern
provinces, Kwangtung, Kwangsi, and Yunnan. An obvious step
towards the execution of such a design would be an attack on the
provincial capital, Canton, an event which was not only anticipated
by the authorities, but was thought feasible, and even probable, by
disinterested onlookers. How little prepared were the Chinese to
resist such an attack will be best understood by the measures they
took to avert it.
An officer of the Chinese customs service, Mr G. Detring, returning
from furlough, brought with him the details of the Marquis Tsêng's
abortive negotiations in Paris. He arrived in China immediately after
the capture of the two strongholds of Sontay and Bacninh. In
proceeding from Hongkong to take up his official post at Canton he
accepted a passage in the French aviso Volta, which conveyed Rear-
Admiral Lespès to the latter city. She was commanded by
Commandant Fournier, with whom Mr Detring had been some years
before on terms of intimacy in the north of China. The principal topic
discussed on the passage was naturally Tongking, and, judging from
subsequent developments, it is reasonable to suppose that the seeds
of the settlement eventually concluded between China and France
were sown during that short but interesting voyage. When Mr
Detring reported himself to the provincial authorities they evinced
the greatest anxiety as to what they conceived to be the threatening
attitude of the French against Canton. Asked if their river defences
were in a position to resist attack, they frankly avowed that they
were not; but yet, being personally responsible for the defence, they
dared not confess the true state of affairs to the Imperial
Government. The viceroy of Canton and the governor of Yunnan
were already under censure, and the military commanders in
Tongking were even threatened with decapitation "pour encourager
les autres." The Canton authorities were thus, in fact, in the dilemma
in which Chinese provincial officials have so frequently found
themselves in dealing with foreign exigencies—responsible yet
helpless. Since they were avowedly incapable of resistance, the
viceroy and governor were advised at once to open negotiations with
the French, and, as a first step, to report the actual position frankly
to the Central Government,—in other words, to Li Hung-chang, who
in this, as in all other crises, had to bear the burden of every
initiative. Having had experience of the capacity of Mr Detring, first
in the negotiating of the Chefoo convention, and subsequently
during several years of official intercourse at Tientsin, Li Hung-chang
moved the Central Government to summon the Canton
commissioner of customs to Tientsin for consultation.
The way being thus partially opened to negotiation, Rear-Admiral
Lespès held himself in readiness to proceed to Tientsin in response
to any invitation that might be conveyed to him. Captain Fournier
was sent on in advance to the rendezvous at Chefoo, where he was
to remain until the real views of the Chinese Government respecting
a settlement of the Tongking dispute had been ascertained. The
French having set their hearts on extorting a large indemnity, it was
emphatically declared to them that China would never pay one
farthing. Any negotiation, therefore, would be futile unless this
question was first eliminated. Having paved the way with Li Hung-
chang, Mr Detring next proceeded to Chefoo to invite Captain
Fournier to Tientsin. From previous good relations he was persona
grata with Li, and on that account was thought a not unfit agent
with whom to discuss preliminaries in anticipation of the arrival of
his admiral. But that there should be no mistake about the
indemnity, Captain Fournier was once more told that unless it were
dropped it would be useless his proceeding to Tientsin. His doing so,
therefore, was a tacit withdrawal of that important item in the
French demands. Both parties being equally desirous of a
settlement, all official technical difficulties were promptly overcome,
and Captain Fournier, from a mere herald of the French admiral, was
by telegraphic instructions from Paris at once promoted to the rank
of plenipotentiary for France, and this notwithstanding that there
was an accredited representative of the Republic eighty miles off in
Peking. The two negotiators, in short, fell into each other's arms,
and the convention of May 11, 1884, was the result.
The peace so suddenly and irregularly patched up was not, however,
destined to endure. Li Hung-chang, knowing better than any of his
peers the risks of a war with France, had stretched his authority to
the uttermost in concluding a treaty which practically ceded Annam
and Tongking to that Power. For though in this as in all his other acts
he carried with him the approval of the empress-dowager, he knew
that he had to brave the ferocious opposition of the ignorant fanatics
of the capital, which he himself described as the "howling of dogs."
The moment the announcement was made, indeed, the furies were
let loose upon him, and he had practically no support but that of the
empress-dowager; for the Tsungli-Yamên, so far as they were not
opposed to the treaty, were invertebrate. It is necessary to bear in
mind this critical position of Li Hung-chang in order to understand
the series of blunders, misunderstandings, recriminations, and actual
war which ensued.
After the ratification of the treaty, arrangements had to be made for
the withdrawal of the Chinese forces from the territory which had
been ceded to France. Captain Fournier, in an interview with Li
Hung-chang, presented a memorandum fixing the dates on which
the troops were to evacuate the several positions specified. A long
discussion appears to have taken place, in which it is not difficult,
from the circumstances above referred to, to divine what the
viceroy's attitude must have been. He wished to avoid the invidious
responsibility of asking the Central Government to order the
withdrawal of the troops from Langson, as to do so would obviously
add fuel to the fire of those powerful functionaries who were
clamouring for the repudiation of the treaty, and for the negotiator's
head. In vain endeavouring to obtain from Fournier an indefinite
delay in carrying out the stipulation for the retirement of the Chinese
troops, Li perhaps trusted that the French commanders in Tongking
would themselves cut the knot by marching forward with an
adequate force and brushing away the Chinese troops opposing
them. The accomplished fact would then have settled everything.
It has been said that the clever interpreter, instead of translating all
the viceroy's arguments and explaining his difficulties, summed the
whole up to Captain Fournier in two words, "Avancez donc"—advice
which would no doubt have been sufficient if only the French military
commander, Colonel Dugenne, had marched with a reasonable force,
or even if he had carried with him a competent interpreter, through
whom he might have communicated with the Chinese commander.
The latter officer, however, when called upon to evacuate the post,
pleaded that he had received no instructions to that effect, and
asked for time to communicate with Peking. The letter to the French
commander containing these reasonable pleas for delay was either
wrongly translated or left untranslated for months. In the meantime
Colonel Dugenne advanced with a small party, and was forced to
retreat with loss, for which he was not unjustly recalled by his own
authorities; and thereupon ensued the Franco-Chinese war.
This was not, however, the only contretemps in connection with this
lamentable outbreak. The Chinese commander had actually
telegraphed to Li Hung-chang for instructions; but, still unwilling to
face the responsibility, the latter left the reply to his council, among
whom there happened to be for the moment his evil genius, Chang
Pei-lun, a fire-eating member of the Tsungli-Yamên, who was on his
way to take up the post of governor of Fukien province and Imperial
Commissioner of the Foochow arsenal.
Laudable efforts were made to repair the mischief, and in the
conferences which followed in Paris peace was more than once all
but assured; but owing to a series of accidents and
misunderstandings, in which the authorities at Peking, the French
representative there, the French commanders on the Chinese coast,
and the telegraph were all implicated, the die was cast in August
1884, and the war was continued till the following April.
For reasons of their own the French Government were averse to
calling the hostilities "war," preferring reprisals and "intelligent
destruction." By whatever name it may be called, the French did not
distinguish themselves greatly in the conduct of the operations.
Their only feat of arms was the destruction, at their anchorage in
the river Min, of the Chinese ships belonging to the Foochow
squadron, and of the arsenal, which, as Li Hung-chang bitterly
reflected, had been erected by "French genius." Admiral Courbet
found his destructive work easy, having entered the river and taken
up a position in the rear of the batteries during time of peace. The
subsequent operations in Formosa were without result; and the
French Government refused permission to Admiral Courbet to attack
Port Arthur, on the non-military ground of wishing to save the
prestige of "notre ami Li Hung-chang." So far as the naval operations
were concerned, even when most successful in intelligent
destruction, they were quite ineffective towards ending the war until
the method which has never failed to bring the Chinese Government
to terms was resorted to—the stoppage of the grain-supply to the
capital. This was accomplished by a patrol of the coast for the
purpose of intercepting vessels carrying rice to Tientsin. The work
performed during the winter and spring of 1885 by the French
cruisers, in keeping the sea without any base and performing their
patrol duties in all weathers, excited the admiration of seamen. It
should be mentioned that they were precluded from acting
offensively against the Yangtze by tacit understanding with Great
Britain and other Powers.
If the breach of the peace between France and China was a
historical curiosity, the eventual settlement of the dispute resembled
a dramatic extravaganza. The final incident of the war in Tongking
was the defeat of the French, followed by a panic, caused apparently
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