SlideShare a Scribd company logo
Get the full ebook with Bonus Features for a Better Reading Experience on ebookgate.com
C 20 for Programmers 3rd Edition P. Deitel
https://ebookgate.com/product/c-20-for-programmers-3rd-
edition-p-deitel/
OR CLICK HERE
DOWLOAD NOW
Download more ebook instantly today at https://ebookgate.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
JavaScript for Programmers 1st Edition Paul J. Deitel
https://ebookgate.com/product/javascript-for-programmers-1st-edition-
paul-j-deitel/
ebookgate.com
C for Java Programmers 1st Edition Harold Cabrera
https://ebookgate.com/product/c-for-java-programmers-1st-edition-
harold-cabrera/
ebookgate.com
C for Java Programmers 1st Edition Dario Laverde
https://ebookgate.com/product/c-for-java-programmers-1st-edition-
dario-laverde/
ebookgate.com
C How to Program 6th Edition Paul Deitel
https://ebookgate.com/product/c-how-to-program-6th-edition-paul-
deitel/
ebookgate.com
C How to Program 9e 9th Edition Paul Deitel
https://ebookgate.com/product/c-how-to-program-9e-9th-edition-paul-
deitel/
ebookgate.com
C How to Program 7th Edition Paul J. Deitel
https://ebookgate.com/product/c-how-to-program-7th-edition-paul-j-
deitel/
ebookgate.com
C How to Program Fourth Edition Harvey M. Deitel
https://ebookgate.com/product/c-how-to-program-fourth-edition-harvey-
m-deitel/
ebookgate.com
Internet World Wide Web How to Program Fourth Edition P.
J. Deitel
https://ebookgate.com/product/internet-world-wide-web-how-to-program-
fourth-edition-p-j-deitel/
ebookgate.com
Herding Cats A Primer for Programmers Who Lead Programmers
1st Edition J. Hank Rainwater
https://ebookgate.com/product/herding-cats-a-primer-for-programmers-
who-lead-programmers-1st-edition-j-hank-rainwater/
ebookgate.com
C 20 for Programmers 3rd Edition P. Deitel
C 20 for Programmers 3rd Edition P. Deitel
Deitel® Developer Series
C++ 20 for Programmers
Paul Deitel • Harvey Deitel
Many of the designations used by manufacturers and sellers to distinguish
their products are claimed as trademarks. Where those designations appear in
this book, and the publisher was aware of a trademark claim, the designations
have been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but
make no expressed or implied warranty of any kind and assume no
responsibility for errors or omissions. No liability is assumed for incidental or
consequential damages in connection with or arising out of the use of the
information or programs contained herein.
Copyright © 2021 Pearson Education, Inc.
All rights reserved. This publication is protected by copyright, and
permission must be obtained from the publisher prior to any prohibited
reproduction, storage in a retrieval system, or transmission in any form or by
any means, electronic, mechanical, photocopying, recording, or likewise. For
information regarding permissions, request forms and the appropriate
contacts within the Pearson Education Global Rights & Permissions
Department, please visit www.pearson.com/permissions.
ISBN-13: 978-0-13-690569-1
ISBN-10: 0-13-690569-1
Contents
Preface
Part 1: C++ Fundamentals Quickstart
Chapter 1. Introduction and Test-Driving a C++ Application
Chapter 2. Introduction to C++ Programming
Chapter 3. Control Statements, Part 1; Intro to C++20 Text
Formatting
Chapter 4. Control Statements, Part 2
Chapter 5. Functions
Part 2: Arrays, Pointers, Strings and Files
Chapter 6. arrays, vectors, C++20 Ranges and Functional-
Style Programming
Chapter 7. (Downplaying) Pointers in Modern C++
Chapter 8. strings, string_views, Text Files, CSV Files and
Regex
Part 3: Object-Oriented Programming
Chapter 9. Custom Classes
Chapter 10. OOP: Inheritance and Runtime Polymorphism
Chapter 11. Operator Overloading, Copy/Move Semantics and
Smart Pointers
Chapter 12. Exceptions and a Look Forward to Contracts
Part 4: Standard Library Containers, Iterators and Algorithms
Chapter 13. Standard Library Containers and Iterators
Chapter 14. Standard Library Algorithms and C++20 Ranges &
Views
Part 5: Advanced Topics
Chapter 15. Templates, C++20 Concepts and Metaprogramming
Chapter 16. C++20 Modules: Large-Scale Development
Chapter 17. Concurrent Programming; Intro to C++20
Coroutines
Part 6: Other Topics
Chapter 18. Stream I/O; C++20 Text Formatting: A Deeper
Look
Chapter 19. Other Topics; A Look Toward C++23 and Contracts
Part 7: Appendices
Appendix A: Operator Precedence and Grouping
Appendix B: Character Set
Appendix C: Fundamental Types
Appendix D: Number Systems
Appendix E: Preprocessor
Appendix F: Bits, Characters, C Strings and structs
Appendix G: C Legacy Code Topics
Appendix H: Using the Visual Studio Debugger
Appendix I: Using the GNU C++ Debugger
Appendix J: Using the Xcode Debugger
Table of Contents
Preface
Part 1: C++ Fundamentals Quickstart
Chapter 1. Introduction and Test-Driving a C++ Application
1.1 Introduction
1.2 Test-Driving a C++20 Application
Chapter 2. Introduction to C++ Programming
2.1 Introduction
2.2 First Program in C++: Displaying a Line of Text
2.3 Modifying Our First C++ Program
2.4 Another C++ Program: Adding Integers
2.5 Arithmetic
2.6 Decision Making: Equality and Relational Operators
2.7 Objects Natural: Creating and Using Objects of Standard
Library Class string
2.8 Wrap-Up
Chapter 3. Control Statements, Part 1; Intro to C++20 Text
Formatting
3.1 Introduction
3.2 Control Structures
3.3 if Single-Selection Statement
3.4 if…else Double-Selection Statement
3.5 while Iteration Statement
3.6 Counter-Controlled Iteration
3.7 Sentinel-Controlled Iteration
3.8 Nested Control Statements
3.9 Compound Assignment Operators
3.10 Increment and Decrement Operators
3.11 Fundamental Types Are Not Portable
3.12 Objects Natural Case Study: Arbitrary Sized Integers
3.13 C++20 Feature Mock-Up—Text Formatting with
Function format
3.14 Wrap-Up
Chapter 4. Control Statements, Part 2
4.1 Introduction
4.2 Essentials of Counter-Controlled Iteration
4.3 for Iteration Statement
4.4 Examples Using the for Statement
4.5 Application: Summing Even Integers
4.6 Application: Compound-Interest Calculations
4.7 do…while Iteration Statement
4.8 switch Multiple-Selection Statement
4.9 C++17: Selection Statements with Initializers
4.10 break and continue Statements
4.11 Logical Operators
4.12 Confusing the Equality (==) and Assignment (=)
Operators
4.13 C++20 Feature Mock-Up: [[likely]] and
[[unlikely]] Attributes
4.14 Objects Natural Case Study: Using the miniz-cpp
Library to Write and Read ZIP files
4.15 C++20 Feature Mock-Up: Text Formatting with Field
Widths and Precisions
4.16 Wrap-Up
Chapter 5. Functions
5.1 Introduction
5.2 Program Components in C++
5.3 Math Library Functions
5.4 Function Definitions and Function Prototypes
5.5 Order of Evaluation of a Function’s Arguments
5.6 Function-Prototype and Argument-Coercion Notes
5.7 C++ Standard Library Headers
5.8 Case Study: Random-Number Generation
5.9 Case Study: Game of Chance; Introducing Scoped enums
5.10 C++11’s More Secure Nondeterministic Random
Numbers
5.11 Scope Rules
5.12 Inline Functions
5.13 References and Reference Parameters
5.14 Default Arguments
5.15 Unary Scope Resolution Operator
5.16 Function Overloading
5.17 Function Templates
5.18 Recursion
5.19 Example Using Recursion: Fibonacci Series
5.20 Recursion vs. Iteration
5.21 C++17 and C++20: [[nodiscard]] Attribute
5.22 Lnfylun Lhqtomh Wjtz Qarcv: Qjwazkrplm xzz
Xndmwwqhlz
5.23 Wrap-Up
Part 2: Arrays, Pointers, Strings and Files
Chapter 6. arrays, vectors, C++20 Ranges and Functional-
Style Programming
6.1 Introduction
6.2 arrays
6.3 Declaring arrays
6.4 Initializing array Elements in a Loop
6.5 Initializing an array with an Initializer List
6.6 C++1 1 Range-Based for and C++20 Range-Based for
with Initializer
6.7 Setting array Elements with Calculations; Introducing
constexpr
6.8 Totaling array Elements
6.9 Using a Primitive Bar Chart to Display array Data
Graphically
6.10 Using array Elements as Counters
6.11 Using arrays to Summarize Survey Results
6.12 Sorting and Searching arrays
6.13 Multidimensional arrays
6.14 Intro to Functional-Style Programming
6.15 Objects Natural Case Study: C++ Standard Library Class
Template vector
6.16 Wrap-Up
Chapter 7. (Downplaying) Pointers in Modern C++
7.1 Introduction
7.2 Pointer Variable Declarations and Initialization
7.3 Pointer Operators
7.4 Pass-by-Reference with Pointers
7.5 Built-In Arrays
7.6 C++20: Using to_array to convert a Built-in Array to a
std::array
7.7 Using const with Pointers and the Data They Point To
7.8 sizeof Operator
7.9 Pointer Expressions and Pointer Arithmetic
7.10 Objects Natural Case Study: C++20 spans—Views of
Contiguous Container Elements
7.11 A Brief Intro to Pointer-Based Strings
7.12 Looking Ahead to Other Pointer Topics
7.13 Wrap-Up
Chapter 8. strings, string_views, Text Files, CSV Files and
Regex
8.1 Introduction
8.2 string Assignment and Concatenation
8.3 Comparing strings
8.4 Substrings
8.5 Swapping strings
8.6 string Characteristics
8.7 Finding Substrings and Characters in a string
8.8 Replacing Characters in a string
8.9 Inserting Characters into a string
8.10 C++11 Numeric Conversions
8.11 C++17 string_view
8.12 Files and Streams
8.13 Creating a Sequential File
8.14 Reading Data from a Sequential File
8.15 C++14 Reading and Writing Quoted Text
8.16 Updating Sequential Files
8.17 String Stream Processing
8.18 Raw String Literals
8.19 Objects Natural Case Study: Reading and Analyzing a
CSV File Containing Titanic Disaster Data
8.20 Objects Natural Case Study: Introduction to Regular
Expressions
8.21 Wrap-Up
Part 3: Object-Oriented Programming
Chapter 9. Custom Classes
9.1 Introduction
9.2 Test-Driving an Account Object
9.3 Account Class with a Data Member and Set and Get
Member Functions
9.4 Account Class: Custom Constructors
9.5 Software Engineering with Set and Get Member Functions
9.6 Account Class with a Balance
9.7 Time Class Case Study: Separating Interface from
Implementation
9.8 Compilation and Linking Process
9.9 Class Scope and Accessing Class Members
9.10 Access Functions and Utility Functions
9.11 Time Class Case Study: Constructors with Default
Arguments
9.12 Destructors
9.13 When Constructors and Destructors Are Called
9.14 Time Class Case Study: A Subtle Trap—Returning a
Reference or a Pointer to a private Data Member
9.15 Default Assignment Operator
9.16 const Objects and const Member Functions
9.17 Composition: Objects as Members of Classes
9.18 friend Functions and friend Classes
9.19 The this Pointer
9.20 static Class Members—Classwide Data and Member
Functions
9.21 Aggregates in C++20
9.22 Objects Natural Case Study: Serialization with JSON
9.23 Wrap-Up
Chapter 10. OOP: Inheritance and Runtime Polymorphism
10.1 Introduction
10.2 Base Classes and Derived Classes
10.3 Relationship between Base and Derived Classes
10.4 Constructors and Destructors in Derived Classes
10.5 Intro to Runtime Polymorphism: Polymorphic Video
Game
10.6 Relationships Among Objects in an Inheritance
Hierarchy
10.7 Virtual Functions and Virtual Destructors
10.8 Abstract Classes and Pure virtual Functions
10.9 Case Study: Payroll System Using Runtime
Polymorphism
10.10 Runtime Polymorphism, Virtual Functions and
Dynamic Binding “Under the Hood”
10.11 Non-Virtual Interface (NVI) Idiom
10.12 Program to an Interface, Not an Implementation
10.13 Runtime Polymorphism with std::variant and std::visit
10.14 Multiple Inheritance
10.15 protected Class Members
10.16 public, protected and private Inheritance
10.17 Wrap-Up
Chapter 11. Operator Overloading, Copy/Move Semantics and
Smart Pointers
11.1 Introduction
11.2 Using the Overloaded Operators of Standard Library
Class string
11.3 Operator Overloading Fundamentals
11.4 (Downplaying) Dynamic Memory Management with
new and delete
11.5 Modern C++ Dynamic Memory Management—RAII and
Smart Pointers
11.6 MyArray Case Study: Crafting a Valuable Class with
Operator Overloading
11.7 C++20 Three-Way Comparison Operator (<=>)
11.8 Converting Between Types
11.9 explicit Constructors and Conversion Operators
11.10 Overloading the Function Call Operator ()
11.11 Wrap-Up
Chapter 12. Exceptions and a Look Forward to Contracts
12.1 Introduction
12.2 Exception-Handling Flow of Control; Defining an
Exception Class
12.3 Exception Safety Guarantees and noexcept
12.4 Rethrowing an Exception
12.5 Stack Unwinding and Uncaught Exceptions
12.6 When to Use Exception Handling
12.7 Constructors, Destructors and Exception Handling
12.8 Processing new Failures
12.9 Standard Library Exception Hierarchy
12.10 C++’s Alternative to the finally Block
12.11 Libraries Often Support Both Exceptions and Error
Codes
12.12 Logging
12.13 Looking Ahead to Contracts
12.14 Wrap-Up
Part 4: Standard Library Containers, Iterators and Algorithms
Chapter 13. Standard Library Containers and Iterators
13.1 Introduction
13.2 Introduction to Containers
13.3 Working with Iterators
13.4 A Brief Introduction to Algorithms
13.5 Sequence Containers
13.6 vector Sequence Container
13.7 list Sequence Container
13.8 deque Sequence Container
13.9 Associative Containers
13.10 Container Adaptors
13.11 bitset Near Container
13.12 Optional: A Brief Intro to Big O
13.13 Optional: A Brief Intro to Hash Tables
13.14 Wrap-Up
Chapter 14. Standard Library Algorithms and C++20 Ranges &
Views
14.1 Introduction
14.2 Algorithm Requirements: C++20 Concepts
14.3 Lambdas and Algorithms
14.4 Algorithms
14.5 Function Objects (Functors)
14.6 Projections
14.7 C++20 Views and Functional-Style Programming
14.8 Intro to Parallel Algorithms
14.9 Standard Library Algorithm Summary
14.10 A Look Ahead to C++23 Ranges
14.11 Wrap-Up
Part 5: Advanced Topics
Chapter 15. Templates, C++20 Concepts and Metaprogramming
15.1 Introduction
15.2 Custom Class Templates and Compile-Time
Polymorphism
15.3 C++20 Function Template Enhancements
15.4 C++20 Concepts: A First Look
15.5 Type Traits
15.6 C++20 Concepts: A Deeper Look
15.7 Testing C++20 Concepts with static_assert
15.8 Creating a Custom Algorithm
15.9 Creating a Custom Container and Iterators
15.10 Default Arguments for Template Type Parameters
15.11 Variable Templates
15.12 Variadic Templates and Fold Expressions
15.13 Template Metaprogramming
15.14 Wrap-Up
Chapter 16. C++20 Modules: Large-Scale Development
16.1 Introduction
16.2 Compilation and Linking Prior to C++20
16.3 Advantages and Goals of Modules
16.4 Example: Transitioning to Modules—Header Units
16.5 Example: Creating and Using a Module
16.6 Global Module Fragment
16.7 Separating Interface from Implementation
16.8 Partitions
16.9 Additional Modules Examples
16.10 Modules Can Reduce Translation Unit Sizes and
Compilation Times
16.11 Migrating Code to Modules
16.12 Future of Modules and Modules Tooling
16.13 Wrap-Up
Chapter 17. Concurrent Programming; Intro to C++20
Coroutines
Part 6: Other Topics
Chapter 18. Stream I/O; C++20 Text Formatting: A Deeper Look
Chapter 19. Other Topics; A Look Toward C++23 and Contracts
Part 7: Appendices
Appendix A: Operator Precedence and Grouping
Appendix B: Character Set
Appendix C: Fundamental Types
Appendix D: Number Systems
Appendix E: Preprocessor
Appendix F: Bits, Characters, C Strings and structs
Appendix G: C Legacy Code Topics
Appendix H: Using the Visual Studio Debugger
Appendix I: Using the GNU C++ Debugger
Appendix J: Using the Xcode Debugger
Preface
Welcome to the C++ programming language and C++20 for Programmers.
This book presents leading-edge computing technologies for software
developers.
These are exciting times in the programming-languages community with each
of the major languages striving to keep pace with compelling new
programming technologies. The ISO C++ Standards Committee now releases
a new standard every three years and the compiler vendors implement the
new features promptly. C++20 for Programmers is based on the new C++20
standard.
Live-Code Approach
At the heart of the book is the Deitel signature live-code approach. We
present most concepts in the context of complete working programs followed
by one or more sample executions. Read the Before You Begin section that
follows this Preface to learn how to set up your Windows, macOS or Linux
computer to run the hundreds of code examples. All the source code is
available at
https://www.deitel.com/c-plus-plus-20-for-programmers
We recommend that you compile and run each program as you study it.
“Rough-Cut” E-Book for O’Reilly Online Learning
Subscribers
You are viewing an early-access “rough cut” of C++20 for Programmers.
We prepared this content carefully, but it has not yet been reviewed or
copy edited and is subject to change. As we complete each chapter, we’ll
post it here. Please send any corrections, comments, questions and
suggestions for improvement to paul@deitel.com and I’ll respond
promptly. Check here frequently for updates.
“Sneak Peek” Videos for O’Reilly Online Learning Subscribers
As an O’Reilly Online Learning subscriber, you also have access to the
“sneak peek” of our new C++20 Fundamentals LiveLessons videos at:
https://learning.oreilly.com/videos/c-20-fundamentals-part
Co-author Paul Deitel immediately records each video lesson as we complete
each rough-cut e-book chapter. Lessons go live on O’Reilly Online Learning
a few days later. Again, check here frequently for updates.
Modern C++
20 The C++ programming language is popular for developing systems
software, embedded systems, operating systems, real-time systems, computer
games, communications systems and other high-performance computer
applications. C++20 for Programmers is an introductory-through-
intermediate-level, professional tutorial presentation of C++. The book is not
a full-language reference manual, nor is it a “cookbook.” We focus on
Modern C++, which consists of the four most recent C++ standards—C++11,
C++14, C++17 and C++20. Throughout the book, features from these
standards are marked with icons in the margins like the 20 icon shown here.
Compilers
We tested every program in the book on three popular free compilers:
• Visual C++ in Microsoft Visual Studio Community edition on Windows,
• Clang in Xcode on macOS, and
• GNU C++ on Linux and in the GNU Compiler Collection (GCC) Docker
container.
At the time of this writing, some C++20 features are fully implemented in all
three compilers, some are implemented in a subset of the three and some are
not implemented at all. We point out these issues as appropriate and will
update our online content as the compiler vendors implement the rest of
C++20’s features. C++20 compiler support for many more compilers is
tracked at
https://en.cppreference.com/w/cpp/compiler_support
We’ll also post updates on the book’s website at
https://deitel.com/books/c-plus-plus-20-for-programmers
Target Audiences
C++20 for Programmers and our C++20 Fundamentals LiveLessons videos
have several target audiences:
• Non-C++ software developers who are about to do a C++ project and
want to learn the latest version of the language, C++20, in the context of
a professional-style, language tutorial.
• Software developers who may have learned C++ in college or used it
professionally some time ago and want to refresh their C++ knowledge in
the context of C++20.
• C++ software developers who want to learn C++20 in the context of a
professional-style, language tutorial.
PERF Security Focus on Performance and Security
Issues
Throughout the book, we call your attention to performance and security
issues with the icons you see here in the margin.
“Objects Natural” Learning Approach
In your C++ programs, you’ll create and use many objects of carefully-
developed-and-tested preexisting classes that enable you to perform
significant tasks with minimal code. These classes typically come from:
• the C++ Standard Library,
• platform-specific libraries, such as those provided by Microsoft
Windows, Apple macOS or various Linux versions,
• free third-party C++ libraries, often created by the open-source
community, and
• libraries created by fellow developers, such as those in your organization.
To help you appreciate this style of programming, early in the book you’ll
create and use objects of preexisting classes before creating your own custom
classes in later chapters. We call this the “objects natural” approach.
Our “Objects Natural” Learning Approach evolved organically as we worked
on our Python for Programmers book
(https://learning.oreilly.com/library/view/python-
for-programmers/9780135231364/) and our Python Fundamentals
LiveLessons videos
(https://learning.oreilly.com/videos/python-
fundamentals/9780135917411), but C++20 for Programmers is the
first book in which we’re using the term, “Objects Natural.”
“Rough-Cut” Table of Contents (Subject to Change)
Part 1: C++ Fundamentals Quickstart
1. Introduction and Test-Driving a C++ Application
2. Introduction to C++ Programming
3. Control Statements, Part 1; Intro to C++20 Text Formatting
4. Control Statements, Part 2
5. Functions
Part 2: Arrays, Pointers, Strings and Files
6. array, vectors, C++20 Ranges and Functional-Style Programming
7. (Downplaying) Pointers in Modern C++
8. string, Regular Expressions and Files
Part 3: Object-Oriented Programming
9. Classes
10. Inheritance and Polymorphism
11. Operator Overloading
12. Exceptions: A Deeper Look
Part 4: Standard Library Containers, Iterators and Algorithms
13. Standard Library Containers and Iterators
14. Standard Library Algorithms; Functional Programming: A Deeper Look
Part 5: Advanced Topics
15. C++20 Modules
16. Intro to Custom Templates and C++20 Concepts
17. Concurrent Programming; Intro to C++20 Coroutines
Part 6: Other Topics
18. Stream I/O; C++20 Text Formatting: A Deeper Look
19. Other Topics; A Look Toward C++23 and Contracts
Part 7: Appendices
A. Operator Precedence and Grouping
B. Character Set
C. Fundamental Types
D. Number Systems
E. Preprocessor
F. Bits, Characters, C Strings and structs
G. C Legacy Code Topics
H. Using the Visual Studio Debugger
I. Using the GNU C++ Debugger
J. Using the Xcode Debugger
Contacting the Authors
As you read the book, if you have questions, we’re easy to reach at
deitel@deitel.com
or
https://deitel.com/contact-us
We’ll respond promptly. For book updates, visit
https://deitel.com/c-plus-plus-20-for-programmers
Join the Deitel & Associates, Inc. Social Media Communities
Join the Deitel social media communities on
• Facebook®—https://facebook.com/DeitelFan
• LinkedIn®—https://bit.ly/DeitelLinkedIn
• Twitter®—https://twitter.com/deitel
• YouTube®—https://youtube.com/DeitelTV
About the Authors
Paul J. Deitel, CEO and Chief Technical Officer of Deitel & Associates,
Inc., is an MIT graduate with 39 years of experience in computing. Paul is
one of the world’s most experienced programming-languages trainers, having
taught professional courses to software developers since 1992. He has
delivered hundreds of programming courses to academic, industry,
government and military clients internationally, including Pearson Education
through O’Reilly Online Learning, Cisco, IBM, Siemens, Sun Microsystems
(now Oracle), Dell, Fidelity, NASA at the Kennedy Space Center, the
National Severe Storm Laboratory, White Sands Missile Range, Rogue Wave
Software, Boeing, Nortel Networks, Puma, iRobot, UCLA and many more.
He and his co-author, Dr. Harvey M. Deitel, are the world’s best-selling
programming-language textbook/professional book/video/webinar authors.
Dr. Harvey M. Deitel, Chairman and Chief Strategy Officer of Deitel &
Associates, Inc., has 59 years of experience in computing. Dr. Deitel earned
B.S. and M.S. degrees in Electrical Engineering from MIT and a Ph.D. in
Mathematics from Boston University— he studied computing in each of
these programs before they spun off Computer Science. He has extensive
college teaching experience, including earning tenure and serving as the
Chairman of the Computer Science Department at Boston College before
founding Deitel & Associates, Inc., in 1991 with his son, Paul. The Deitels’
publications have earned international recognition, with more than 100
translations published in Japanese, German, Russian, Spanish, French, Polish,
Italian, Simplified Chinese, Traditional Chinese, Korean, Portuguese, Greek,
Urdu and Turkish. Dr. Deitel has delivered hundreds of programming courses
to academic, corporate, government and military clients.
About Deitel® & Associates, Inc.
Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an
internationally recognized authoring and corporate training organization,
specializing in computer programming languages, object technology, mobile
app development and Internet-and-web software technology. The company’s
training clients include some of the world’s largest companies, government
agencies, branches of the military, and academic institutions. The company
offers instructor-led training courses delivered at client sites worldwide on
major programming languages.
Through its 45-year publishing partnership with Pearson/Prentice Hall, Deitel
& Associates, Inc., publishes leading-edge programming textbooks and
professional books in print and e-book formats, LiveLessons video courses,
O’Reilly Online Learning live webinars and Revel™ interactive
multimedia courses.
To learn more about Deitel on-site corporate training, visit
https://deitel.com/training
To request a proposal for on-site, instructor-led training worldwide, write to:
deitel@deitel.com
Individuals wishing to purchase Deitel books can do so at
https://www.amazon.com
Bulk orders by corporations, the government, the military and academic
institutions should be placed directly with Pearson. For more information,
visit
https://www.informit.com/store/sales.aspx
Part 1: C++ Fundamentals Quickstart
Chapter 1. Introduction and Test-Driving a
C++ Application
C 20 for Programmers 3rd Edition P. Deitel
Objectives
In this chapter, you’ll do one or more of the following:
■ Test-drive a C++20 application in the Visual C++ compiler in
Microsoft Visual Studio Community edition on Windows.
■ Test-drive a C++20 application in the Clang compiler in Xcode on
macOS.
■ Test-drive a C++20 application in the GNU C++ compiler on Linux.
■ Test-drive a C++20 application in the GNU Compiler Collection
(GCC) Docker Container in Docker running natively over Windows
10, macOS and/or Linux.
1.1 Introduction
1.2 Test-Driving a C++20 Application
1.2.1 Compiling and Running a C++20 Application with Visual
Studio 2019 Community Edition on Windows 10
1.2.2 Compiling and Running a C++20 Application with Xcode
on macOS
1.2.3 Compiling and Running a C++20 Application with GNU
C++ on Linux
1.2.4 Compiling and Running a C++20 Application with GNU
C++ in the GCC Docker Container in Docker Running
Natively Over Windows 10, macOS and/or Linux
1.1 Introduction
Welcome to C++—one of the world’s most widely used, high-performance,
computer-programming languages—and its current version C++20.
If you’re reading this, you’re on the O’Reilly Online Learning platform
(formerly called Safari) viewing an early-access Rough Cut of our
forthcoming book C++20 for Programmers, scheduled for publication this
summer. We have prepared this content carefully, but it has not yet been
peer reviewed or copy edited and is subject to change. When we complete
this chapter, we’ll post the reviewed and copy edited version here.
Please send any corrections, comments, questions and suggestions for
improvement to paul@deitel.com and I’ll respond promptly. Check for
updates here and on the book’s web page:
https://deitel.com/c-plus-plus-20-for-programmers
This book is written for developers using one or more of the following
popular desktop platforms—Microsoft Windows 10, macOS and Linux. We
tested every program on three popular free compilers:
• Visual C++ in Microsoft Visual Studio Community edition on Windows
10,
• Clang in Xcode on macOS, and
• GNU C++ on Linux and in the GNU Compiler Collection (GCC) Docker
container.1
1. At Deitel, we use current, powerful multicore Apple Mac computers that enable us to run macOS
natively, and Windows 10 and Linux through virtual machines in VMWare Fusion. Docker runs
natively on Windows, macOS and Linux systems.
This early-access version of Chapter 1 contains test-drives demonstrating
how to compile and run a C++20 application using these compilers and
platforms. The published version of this chapter will contain additional
introductory material.
At the time of this writing, some C++20 features are fully implemented in all
three compilers, some are implemented in a subset of the three and some are
not implemented at all. We point out these issues as appropriate and will
update our online content as the compiler vendors implement the rest of
C++20’s features. C++20 compiler support for many more compilers is
tracked at:
https://en.cppreference.com/w/cpp/compiler_support
“Sneak Peek” Videos for O’Reilly Online Learning Subscribers
As an O’Reilly Online Learning subscriber, you also have access to the
“sneak peek” of our new C++20 Fundamentals LiveLessons videos at:
https://learning.oreilly.com/videos/c-20-fundamentals-part
Co-author Paul Deitel immediately records each video lesson as we complete
the corresponding chapter. Lessons go live on O’Reilly Online Learning a
few days later. Again, check here frequently for updates.
1.2 Test-Driving a C++20 Application
In this section, you’ll compile, run and interact with your first C++
application—a guess-the-number game, which picks a random number from
1 to 1000 and prompts you to guess it. If you guess correctly, the game ends.
If you guess incorrectly, the application indicates whether your guess is
higher or lower than the correct number. There’s no limit on the number of
guesses you can make.
Usually, this application randomly selects the correct answer as you execute
the program. We’ve disabled that aspect of the application so that it uses the
same correct answer every time the program executes (though this may vary
by compiler). So, you can use the same guesses we use and see the same
results.
Summary of the Test-Drives
We’ll demonstrate running a C++ application using:
• Microsoft Visual Studio 2019 Community edition for Windows (Section
1.2.1)
• Clang in Xcode on macOS (Section 1.2.2).
• GNU C++ in a shell on Linux (Section 1.2.3)
• GNU C++ in a shell running inside the GNU Compiler Collection (GCC)
Docker container. This requires Docker to be installed and running.
You need to read only the section that corresponds to your platform. At the
time of this writing, GNU C++ supports the most C++20 features of the three
compilers we use.
1.2.1 Compiling and Running a C++20 Application with Visual
Studio 2019 Community Edition on Windows 10
In this section, you’ll run a C++ program on Windows using Microsoft
Visual Studio 2019 Community edition. There are several versions of Visual
Studio available—on some versions, the options, menus and instructions we
present might differ slightly. From this point forward, we'll simply say
“Visual Studio” or “the IDE.”
Step 1: Checking Your Setup
If you have not already done so, read the Before You Begin section of this
book for instructions on installing the IDE and downloading the book’s code
examples.
Step 2: Launching Visual Studio
Open Visual Studio from the Start menu. The IDE displays the following
Visual Studio 2019 window containing:
Close this window for now by clicking the X in its tab—you can access this
window any time by selecting File > Start Window. We use the > character
to indicate selecting a menu item from a menu. For example, the notation File
> Open indicates that you should select the Open menu item from the File
menu.
Step 3: Creating a Project
A project is a group of related files, such as the C++ source-code files that
compose an application. Visual Studio organizes applications into projects
and solutions, which contain one or more projects. Multiple-project solutions
are used to create large-scale applications. Each application in this book
requires only a single-project solution.
To work our code examples, you’ll begin with an Empty Project and add
files to it. To create a project:
1. Select File > New > Project… to display the Create a New Project
dialog:
2. In the preceding dialog, select the Empty Project template with the
tags C++, Windows and Console. This template is for programs that
execute at the command line in a Command Prompt window.
Depending on the version of Visual Studio you’re using and the options
you have installed, there may be many other project templates installed.
You can narrow down your choices using the Search for templates
textbox and the drop-down lists below it. Click Next to display the
Configure your new project dialog:
3. Provide a Project name and Location for your project. For the Project
name, we specified cpp20_test. For the Location, we selected the
examples folder containing this book’s code examples. Click Create
to open your new project in Visual Studio.
At this point, the Visual Studio creates your project, places its folder in
C:UsersYourUserAccountDocumentsexamples
(or the folder you specified) and opens the main window:
This window displays editors as tabbed windows (one for each file) when
you’re editing code. On the left side is the Solution Explorer for viewing
and managing your application’s files. In this book’s examples, you’ll
typically place each program’s code files in the Source Files folder. If the
Solution Explorer is not displayed, you can display it by selecting View >
Solution Explorer.
Step 4: Adding the GuessNumber.cpp File into the Project
Next, you’ll add GuessNumber.cpp to the project you created in Step 3.
In the Solution Explorer:
1. Right-click the Source Files folder and select Add > Existing Item….
2. In the dialog that appears, navigate to the ch01 subfolder of the book’s
examples folder, GuessNumber.cpp and click Add.2
2. For the multiple source-code-file programs that you’ll see in later chapters, select all the files for a
given program. When you begin creating programs yourself, you can right click the Source Files
folder and select Add > New Item… to display a dialog for adding a new file.
Step 5: Configuring Your Project to Use C++20
The Visual C++ compiler in Visual Studio supports several versions of the
C++ standard. For this book, we use C++20, which we must configure in our
project’s settings:
1. Right-click the project’s node— —in the Solution Explorer and
select Properties to display the project’s cpp20_test Property Pages
dialog:
2. In the left column, expand the C/C++ node, then select Language.
3. In the right column, click in the field to the right of C++ Language
Standard, click the down arrow, then select Preview - Features from
the Latest C++ Working Draft (/std:c++latest) and click OK. In a
future version of Visual Studio, Microsoft will change this option to
ISO C++20 Standard (/std:c++20).
Step 6: Compiling and Running the Project
To compile and run the project so you can test-drive the application, select
Debug > Start without debugging or type Ctrl + F5. If the program
compiles correctly, Visual Studio opens a Command Prompt window and
executes the program. We changed the Command Prompt’s color scheme and
font size for readability:
Step 7: Entering Your First Guess
At the ? prompt, type 500 and press Enter. The application displays "Too
high. Try again." to indicate the value you entered is greater than the
number the application chose as the correct guess:
Step 8: Entering Another Guess
At the next prompt, type 250 and press Enter. The application displays
"Too high. Try again.", because the value you entered once again is
greater than the correct guess:
Step 9: Entering Additional Guesses
Continue to play the game by entering values until you guess the correct
number. When you guess correctly, the application displays "Excellent!
You guessed the number!":
Step 10: Playing the Game Again or Exiting the Application
After you guess the correct number, the application asks if you’d like to play
another game. At the "Would you like to play again (y or
n)?" prompt, entering y causes the application to choose a new number and
start a new game. Entering n terminates the application. Each time you
execute this application from the beginning (Step 6), it will choose the same
numbers for you to guess.
Reusing This Project for Subsequent Examples
You can follow the steps in this section to create a separate project for every
application in the book. However, for our examples, you may find it more
convenient to remove the current program from the project then add a new
one. To remove a file from your project (but not your system), select it in the
Solution Explorer then press Del (or Delete). You can then repeat Step 4 to
add a different program to the project.
1.2.2 Compiling and Running a C++20 Application with Xcode
on macOS
In this section, you’ll run a C++ program on a macOS using the Clang
compiler in Apple’s Xcode IDE.
Step 1: Checking Your Setup
If you have not already done so, read the Before You Begin section of this
book for instructions on installing the IDE and downloading the book’s code
examples.
Step 2: Launching Xcode
Open a Finder window, select Applications and double-click the Xcode icon
( ). If this is your first time running Xcode, the Welcome to Xcode
window appears:
Close this window by clicking the X in the upper left corner—you can access
it any time by selecting Window > Welcome to Xcode. We use the >
character to indicate selecting a menu item from a menu. For example, the
notation File > Open… indicates that you should select the Open… menu
item from the File menu.
Step 3: Creating a Project
A project is a group of related files, such as the C++ source-code files that
compose an application. The Xcode projects we created for this book’s
examples are Command Line Tool projects that you’ll execute directly in
the IDE. To create a project:
1. Select File > New > Project….
2. At the top of the Choose a template for your new project dialog,
click macOS.
3. Under Application, click Command Line Tool and click Next.
4. For Product Name, enter a name for your project—we specified
cpp20_test.
5. In the Language drop-down list, select C++ then click Next.
6. Specify where you want to save your project. We selected the
examples folder containing this book’s code examples.
7. Click Create.
Xcode creates your project and displays the workspace window initially
showing three areas—the Navigator area, Editor area and Utilities area:
The left-side Navigator area has icons at its top for the navigators that can be
displayed there. For this book, you’ll primarily work with
• Project ( )—Shows all the files and folders in your project.
• Issue ( )—Shows you warnings and errors generated by the compiler.
Clicking a navigator button displays the corresponding navigator panel.
The middle Editor area is for managing project settings and editing source
code. This area is always displayed in your workspace window. Selecting a
file in the Project navigator, the file’s contents display in the Editor area.
You will not use the right-side Utilities area in this book. There’s also a
Debug area in which you’ll run and interact with the guess-the-number
program. This will appear below the Editor area.
The workspace window’s toolbar contains options for executing a program:
displaying the progress of tasks executing in Xcode:
and hiding or showing the left (Navigator), right (Utilities) and bottom
(Debug) areas:
Step 4: Configuring the Project to Compile Using C++20
The Clang compiler in Xcode supports several versions of the C++ standard.
For this book, we use C++20, which we must configure in our project’s
settings:
1. In the Project navigator, select your project’s name (cpp20_test).
2. In the Editors area’s left side, select your project’s name under
TARGET.
3. At the top of the Editors area, click Build Settings, and just below it,
click All.
4. Scroll to the Apple Clang - Language - C++ section.
5. Click the value to the right of C++ Language Dialect and select
Other….
6. In the popup area, replace the current setting with c++2a and press
Enter. In a future version of Xcode, Apple will provide a C++20 option
for C++ Language Dialect.
Step 5: Deleting the main.cpp File from the Project
By default, Xcode creates a main.cpp source-code file containing a simple
program that displays "Hello, World!". You won’t use main.cpp in
this test-drive, so you should delete the file. In the Project navigator, right-
click the main.cpp file and select Delete. In the dialog that appears, select
Move to Trash. The file will not be removed from your system until you
empty your trash.
Step 6: Adding the GuessNumber.cpp File into the Project
In a Finder window, open the ch01 folder in the book’s examples folder,
then drag GuessNumber.cpp onto the Guess Number folder in the
Project navigator. In the dialog that appears, ensure that Copy items if
needed is checked, then click Finish.3
3. For the multiple source-code-file programs that you’ll see later in the book, drag all the files for a
given program to the project’s folder. When you begin creating your own programs, you can right
click the project’s folder and select New File… to display a dialog for adding a new file.
Step 7: Compiling and Running the Project
To compile and run the project so you can test-drive the application, simply
click the run ( ) button on Xcode’s toolbar. If the program compiles
correctly, Xcode opens the Debug area and executes the program in the right
half of the Debug area:
The application displays "Please type your first guess.", then
displays a question mark (?) as a prompt on the next line.
Step 8: Entering Your First Guess
Click in the Debug area, then type 500 and press Return
The application displays "Too low. Try again.", meaning that the
value you entered is less than the number the application chose as the correct
guess.
Step 9: Entering Another Guess
At the next prompt, enter 750:
The application displays "Too low. Try again.", because the value
you entered once again is less than the correct guess.
Step 10: Entering Additional Guesses
Continue to play the game by entering values until you guess the correct
number. When you guess correctly, the application displays "Excellent!
You guessed the number.":
Playing the Game Again or Exiting the Application
After you guess the correct number, the application asks if you’d like to play
another game. At the "Would you like to play again (y or
n)?" prompt, entering y causes the application to choose a new number and
start a new game. Entering n terminates the application. Each time you
execute this application from the beginning (Step 7), it will choose the same
numbers for you to guess.
Reusing This Project for Subsequent Examples
You can follow the steps in this section to create a separate project for every
application in the book. However, for our examples, you may find it more
convenient to remove the current program from the project then add a new
one. To remove a file from your project (but not your system), right-click the
file in the Project navigator and select Delete. In the dialog that appears,
select Move to Trash. You can then repeat Step 6 to add a different program
to the project.
1.2.3 Compiling and Running a C++20 Application with GNU
C++ on Linux
For this test drive, we assume that you read the Before You Begin section and
that you placed the downloaded examples in your user account’s
Documents folder.
Step 1: Changing to the ch01 Folder
From a Linux shell, use the cd command to change to the ch01 subfolder of
the book’s examples folder:
Click here to view code image
~$ cd ~/Documents/examples/ch01
~/Documents/examples/ch01$
In this section’s figures, we use bold to highlight the text that you type. The
prompt in our Ubuntu Linux shell uses a tilde (~) to represent the home
directory. Each prompt ends with the dollar sign ($). The prompt may differ
on your Linux system.
Step 2: Compiling the Application
Before running the application, you must first compile it:
Click here to view code image
~/Documents/examples/ch01$ g++ -std=c++2a GuessNumber.cpp -
~/Documents/examples/ch01$
The g++ command compiles the application:
• The -std=c++2a option indicates that we’re using C++20—c++2a
will become c++20 in a future GNU C++ release.
• The -o option names the executable file (GuessNumber) that you’ll
use to run the program.
Step 3: Running the Application
Type ./GuessNumber at the prompt and press Enter to run the program:
Click here to view code image
~/Documents/examples/ch01$ ./GuessNumber
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess.
?
The ./ tells Linux to run a file from the current directory and is required to
indicate that GuessNumber is an executable file.
Step 4: Entering Your First Guess
The application displays "Please type your first guess.", then
displays a question mark (?) as a prompt on the next line. At the prompt,
enter 500—note that the outputs may vary based on the compiler you’re
using:
Click here to view code image
~/Documents/examples/ch01$ ./GuessNumber
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess.
? 500
Too high. Try again.
?
The application displays "Too high. Try again.", meaning that the
value you entered is greater than the number the application chose as the
correct guess.
Step 5: Entering Another Guess
At the next prompt, enter 250:
Click here to view code image
~/Documents/examples/ch01$ ./GuessNumber
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess.
? 500
Too high. Try again.
? 250
Too low. Try again.
?
This time the application displays "Too low. Try again.", because
the value you entered is less than the correct guess.
Step 6: Entering Additional Guesses
Continue to play the game by entering values until you guess the correct
number. When you guess correctly, the application displays "Excellent!
You guessed the number.":
Click here to view code image
Too low. Try again.
? 375
Too low. Try again.
? 437
Too high. Try again.
? 406
Too high. Try again.
? 391
Too high. Try again.
? 383
Too low. Try again.
? 387
Too high. Try again.
? 385
Too high. Try again.
? 384
Excellent! You guessed the number.
Would you like to play again (y or n)?
Step 7: Playing the Game Again or Exiting the Application
After you guess the correct number, the application asks if you’d like to play
another game. At the "Would you like to play again (y or
n)?" prompt, entering y causes the application to choose a new number and
start a new game. Entering n terminates the application and returns you to the
shell. Each time you execute this application from the beginning (Step 3), it
will choose the same numbers for you to guess.
1.2.4 Compiling and Running a C++20 Application with GNU
C++ in the GCC Docker Container in Docker Running
Natively Over Windows 10, macOS and/or Linux
At the time of this writing, GNU C++ implements the most C++20 features.
For this reason, you may want to use the latest GNU C++ compiler on your
system. One of the most convenient cross-platform ways to do this is by
using the GNU Compiler Collection (GCC) Docker container. This section
assumes you’ve already installed Docker Desktop (Windows or macOS) or
Docker Engine (Linux).
Executing the GNU Compiler Collection (GCC) Docker Container
Open a Command Prompt (Windows), Terminal (macOS/Linux) or shell
(Linux), then perform the following steps to launch the GCC Docker
Container:
1. Use the cd command to navigate to the examples folder containing
this book’s examples.
2. Windows users: Launch the GCC docker container with the command
Click here to view code image
docker run --rm -it -v "%CD%":/usr/src gcc:latest
3. macOS/Linux users: Launch the GCC docker container with the
command
Click here to view code image
docker run --rm -it -v "$(pwd)":/usr/src gcc:latest
In the preceding commands:
• --rm cleans up the container’s resources when you eventually shut it
down.
• -it runs the container in interactive mode, so you can enter commands
to change folders and to compile and run programs using the GNU C++
compiler.
• -v "%CD%":/usr/src (Windows) or -v "$(pwd)":/usr/src
(macOS/Linux) allows the Docker container to access your local system
files in the folder from which you executed the docker run command.
In the Docker container, you’ll navigate with the cd command to
subfolders of /usr/src to compile and run the C++ code.
• gcc:latest is the container name. The :latest specifies that you
want to use the most up-to-date version of the gcc container. Each time
you execute the preceding docker run commands, Docker checks
whether you have the latest gcc container version. If not, Docker
downloads it before executing the container.
Once the container is running, you’ll see a prompt like:
root@67773f59d9ea:/#
The container uses a Linux operating system. It’s prompt displays the current
folder location between the : and #.
Changing to the ch01 Folder in the Docker Container
The docker run command specified above attaches your examples
folder to the containers /usr/src folder. In the docker container, use the
cd command to change to the ch01 sub-folder of /usr/src:
Click here to view code image
root@01b4d47cadc6:/# cd /usr/src/ch01
root@01b4d47cadc6:/usr/src/ch01#
To compile, run and interact with the GuessNumber application in the
Docker container, follow Steps 2–7 of Section 1.2.3’s GNU C++ Test-Drive.
Terminating the Docker Container
You can terminate the Docker container by typing Ctrl + d at the container’s
prompt.
Chapter 2. Introduction to C++
Programming
C 20 for Programmers 3rd Edition P. Deitel
Objectives
In this chapter, you’ll:
■ Write simple C++ applications.
■ Use input and output statements.
■ Use fundamental data types.
■ Use arithmetic operators.
■ Understand the precedence of arithmetic operators.
■ Write decision-making statements.
■ Use relational and equality operators.
■ Begin appreciating the “objects natural” learning approach by
creating and using objects of the C++ standard library’s string
class before creating your own custom classes.
Outline
2.1 Introduction
2.2 First Program in C++: Displaying a Line of Text
2.3 Modifying Our First C++ Program
2.4 Another C++ Program: Adding Integers
2.5 Arithmetic
2.6 Decision Making: Equality and Relational Operators
2.7 Objects Natural: Creating and Using Objects of Standard Library
Class string
2.8 Wrap-Up
2.1 Introduction
This chapter presents several code examples that demonstrate how your
programs can display messages and obtain data from the user for processing.
The first three display messages on the screen. The next obtains two numbers
from a user at the keyboard, calculates their sum and displays the result—the
Another Random Scribd Document
with Unrelated Content
Aug. 14.
Aug. 15.
Divisions) under Sir Douglas Haig, at Wassigny; the Headquarters of
the Second Corps (the Third and Fifth Divisions), under Sir Horace
Smith-Dorrien, at Nouvion; while the Cavalry Division, under General
Allenby, was sent to Maubeuge.
It was a scorching, airless day, and the
march to camp was a very trying one. But
after a good sleep and a bathe in the sea the men were thoroughly
refreshed and fit. Then, after the usual inspections, they were
formed up on parade, and the King's message was read out to them:
Message from the King to the Troops of the Expeditionary Force
You are leaving home to fight for the safety and honour of my empire.
Belgium, whose Country we are pledged to defend, has been attacked and
France is about to be invaded by the same powerful foe.
I have implicit confidence in you, my soldiers. Duty is your watchword, and I
know your duty will be nobly done.
I shall follow your every movement with deepest interest and mark with eager
satisfaction your daily progress, indeed your welfare will never be absent from
my thoughts.
I pray God to bless you and guard you and bring you back victorious.
George R.I.
The whole population of Havre seemed to have come out to see the
Battalion when it marched the same evening to the entraining point.
The crowd cheered and shouted, and the men responded with "The
Marseillaise." When they reached the siding the disappointing news
met them that the train would not start for another four hours. It
began to rain heavily, but fortunately there were large hangars
available, into which the men crowded for shelter.
Eventually when the train arrived at 2 A.M.,
the men were packed into it, and very
crowded they were. Sleep was difficult, as the horse-wagons
attached to the train were loosely coupled, and there was a
succession of bumps whenever the train stopped or slowed down.
The first real stop was at Rouen, where provisions were obtained for
the men, and then the train bumped on to Amiens.
Route of the Second Battalion,
1914
Fervent scenes of welcome went on all along the line. Each little
wayside station, every bridge and level-crossing held a cheering
throng. At Arras the Mayor turned out in state with a number of local
magnates, and presented three large bouquets, for which Colonel
Corry returned thanks on behalf of the officers, in his best French.
Aug. 16-20.
Aug. 20-22.
A touch of humour was not wanting at the little ceremony—if any
one had been in the mood to seize hold of it. For, caught unawares,
Colonel Corry, Lord Loch, and Lord Bernard Gordon-Lennox were
anything but arrayed for a function, in fact, in a state of decided
deshabille. But such was the enthusiasm of the inhabitants that a
trifle like this passed unnoticed or unconsidered.
The stationmaster here said he was passing trains through at the
rate of one every ten or fifteen minutes, which gives some idea of
the great concentration of troops that was going on.
Slowly the train went on through Cambrai, Busigny, and Vaux
Andigny to Flavigny, where, in pouring rain, the Battalion detrained
and went into billets—surprisingly well arranged; but then Flavigny
had plenty of experience in that way, and only a few days before
had lodged the French troops.
Next morning parade was at 7 o'clock for
the march to Grougis, about seven and a
half miles off, where four days were spent in billets, and Colonel
Corry took advantage of the breathing space to have his officers and
men inoculated against typhoid.
The concentration of the British Force in the Busigny area was now
completed, and the advance towards Mons was to begin the next
day.
Off again on the 20th, the Battalion
marched to Oisy (where it was again
billeted), and on the following days to Maroilles and La Longueville.
Here for the first time it heard the guns, and realised that very soon
it would be getting to work.
On the 21st, following the plan concerted with General Joffre, Sir
John French took up a defensive position from Condé on the west to
Binche to the east—a front of about twenty-five miles. The British
Army was thus on the extreme left of the French lines. To the First
Corps was assigned the easterly position from Mons to Binche, while
Aug. 23.
the Second Corps lined the canal from Mons to Condé, the whole
front being covered by the 5th Cavalry Brigade.
Originally the scheme appears to have been to await the enemy's
onslaught on the Charleroi—Mons line, and then to assume the
offensive and advance into Belgium.
How far-reaching the German preparations had been was at that
time hardly recognised, and neither the French nor the British
Commander-in-Chief seems to have had any conception of the
overwhelming force which the Germans had been able to
concentrate against them.
From La Longueville the 2nd Battalion
Grenadiers marched on August 23, during
the last stages of its journey, across the field of Malplaquet, where
more than 200 years before the regiment had fought with
distinction, through Blaregnies and Genly to the outskirts of Mons,
where it bivouacked. There it received orders to advance, which
were countermanded before they could be carried out, and the
Battalion was told to remain where it was. There was nothing to do
but have breakfast and an hour's sleep by the roadside, with
showers falling at intervals. All the time heavy firing could be heard
from the direction of Mons, and shells bursting could be observed in
the distance.
Orders then came for the Battalion to march back to Quevy le Petit,
about five miles off, where the men fondly imagined they would
again be comfortably billeted. But hardly had they arrived there
when they were sent forward again. As they were marching down a
dusty track General Scott-Kerr rode up, and directed the 2nd
Battalion Grenadiers and the Irish Guards to move up close behind
the ridge east of Spiennes in support of the Irish Rifles. At the same
time the two Coldstream battalions were ordered to entrench
themselves just east of Harveng, presumably as a precaution in case
the Brigade should have to retire. Heavy firing was now going on all
round, and the ridge which overlooked St. Symphorien to the north
was being vigorously shelled by the Germans, who had got the
range to a nicety, and were bursting their shells over it with
accuracy. It was about 6 P.M. when the Battalion, advancing through
Harveng, proceeded in artillery formation for about one and a half
miles to the hill near Spiennes. The men huddled close together
under the banks on the reverse slope of the hill just over the railway
line, while bullets and shells whistled over their heads. As they were
lying there they were amused to see the signalman walk slowly
down the line as if nothing in particular was happening. He had to
light the lamps, and saw no reason why the ordinary routine which
he had carried out probably for many years should be interfered
with. One of the officers called out to him in French, and explained
that the Germans were advancing, but he merely murmured "ça
m'est égal," and continued his work, apparently unconscious of the
bullets that were striking the line.
Meanwhile, Colonel Corry and Major Jeffreys went up to the position
occupied by the Irish Rifles, who were holding their own well under
a heavy rifle fire.
When they returned to their men it was getting dark, and at 10.30 a
message came from the O.C. Irish Rifles, that his battalion was
retiring. It appeared therefore to Colonel Corry that the position was
becoming untenable, since the Irish Rifles on his left had already
retired, and both flanks of the Battalion were exposed. He consulted
Colonel Morris of the Irish Guards, and they both came to the
conclusion that the best course would be to retire to Harveng.
The difficulty was to communicate with the Brigadier. The telephone
to Brigade Headquarters had been cut by shell-fire, and so Colonel
Corry rode back to find General Scott-Kerr. He could not be
discovered, and was reported to have gone to Divisional
Headquarters. There seemed no prospect whatever of finding him,
and it was now past midnight. Thereupon Colonel Corry determined
to take upon himself the responsibility of ordering the retirement of
the two battalions. His impression was that in a case like this, when
local conditions could not be known to the Divisional Staff, it was for
the man on the spot to make his own decision.
Aug. 24.
Superior authority, however, afterwards held that while under
exceptional circumstances such powers might well be delegated to
the man in mediis rebus, in a case like this it could not be admitted
that an officer in actual touch with the enemy was the best judge of
how long a position should be held. It was felt that there were many
considerations in a decision of this sort, of which the officer in the
front line could know very little. Colonel Corry was therefore severely
blamed for his action, and was a fortnight later relieved of his
command.
At 1 o'clock in the morning the 2nd
Battalion Grenadiers and the Irish Guards
retired, but they had only gone a couple of miles towards Harveng
when they were ordered to go back and occupy the ridge they had
just left. Back they went, and got as far as the foot of the hill, only
to receive another order to retire to Harveng. By this time the men
were absolutely tired out. They had started at 3.30 the previous
morning, and had been on the move for twenty-four hours, with only
occasional halts by the roadside.
It was just at this point in the engagement that Sir John French
received what he described in his despatch as a most unexpected
message. It came from General Joffre, who informed him that the
French Forces had been compelled, by superior numbers, to retire,
and that consequently the Fifth French Army, which was immediately
on our right, had vacated its line. Two German corps were advancing
on the British position, while a third corps was engaged in a turning
movement in the direction of Tournai. Divisions of French Territorials
had been promised in support of the left flank, but, except for a
Brigade at Tournai, no French troops arrived from the west. There
was therefore no alternative for Sir John French but to retire.
Aug. 24.
CHAPTER III
THE RETREAT FROM MONS (2ND BATTALION)
Thus began that historic, terrible, splendid retreat from Mons. Long
weary marches were to be the lot of the British Army for many a
day, but fortunately no one realised what lay ahead, or the stoutest
hearts might well have quailed.
Long before it was over, the men's boots—not Crimean ones of
brown paper, but good, sound English leather—had been worn into
shreds by those interminable, pitiless paving-stones, that had
withstood centuries of traffic. Even the men with the toughest skins
suffered badly from their feet. Clouds of dust and the heavy
atmosphere arising from men in close formation added to the trials
of marching. Constant cries of "Feel your right" (to let cavalry or
wagons pass by), the wearisome burden of the pack on the
shoulders, which drove many men to throw away their most prized
possessions, the frequent futile digging of trenches, abandoned as
soon as they were dug, the orders and counter-orders—all made the
days that followed a positive nightmare to the Army.
Such continuous retirement had never been practised. It was against
all tradition, and the men grumbled constantly at the seemingly
never-ending retreat. But what other course could the "contemptible
little army" have followed in the face of the enemy's overwhelming
force?
On the 24th Sir H. Smith-Dorrien started off
with the Second Corps, while a
demonstration was made by the First Corps in the direction of
Binche, and dug a line four miles south of Mons to enable the First
Corps to retire. It was evident that the Germans were straining every
effort to surround the British Army, and therefore to hold on too long
to any line was extremely dangerous. The Fifth French Army was still
in full retirement, and the First French Cavalry Corps was so
exhausted that General Sordet could promise no assistance. The
greater part of the British Cavalry Division, with the exception of the
regiments covering the retreat of the two British Corps, was
guarding the left flank. The arrival of the Fourth Division at Le
Cateau had been a welcome addition, but as it was only too
probable that the Germans would make every effort to envelop the
left of the whole line of the Allies, it was important to have strong
reinforcements on that flank.
C 20 for Programmers 3rd Edition P. Deitel
Aug. 25.
Landrecies.
Route taken by the Second Batt. Grenadier Guards during the
Retreat from Mons, and subsequent advance to the Marne
and the Aisne. 1914.
Two hours' sleep was all the 2nd Battalion Grenadiers was allowed
on that fateful 24th of August, weary as it was after its twenty-four
hours on end of marching and fighting. At daybreak it marched to
Quevy le Grand, where the men were ordered to dig themselves in.
They were quite in the dark about what was going on round them.
What force was opposed to them or why they were retiring, no one
knew. The greatest secrecy prevailed. Although it was cold and
foggy early, it soon became scorching hot and the men were tired,
but when the word went round that this was not a rearguard action,
but a determined stand, the digging became a serious matter, and
they set to with a will. The Germans advanced very slowly and
cautiously, gradually pushing back our Cavalry Patrols, who could be
seen retiring. They shelled the Mons—Maubeuge Road and also
Quevy le Grand, but as the line of the road was not held, our
position being some hundreds of yards in rear of it, little damage
was done, although a few men were hit in the village.
But at 2 P.M. another order came to evacuate the trenches and
concentrate on the left. "Concentration" proved to be a euphemism
for further retirement, and after a long and dusty march the
Battalion bivouacked south of La Longueville.
Next morning at 5 o'clock it started on
another hot and lengthy march through
Pont sur Sambre, Leval, and Noyelles to Landrecies, which was
reached at 4 P.M. It went into billets and settled down to rest. But
soon afterwards a trooper from the cavalry patrols rode into the
town with the news that the Germans were coming; the alarm was
given, and the men stood to arms. Nothing further happened,
however, and they returned to their billets. The 3rd Battalion
Coldstream provided the outposts, and the rest of the brigade were
just settling down once more in the hope of a restful night when a
second alarm sounded. This time it was a real one. The Germans
were advancing in force on Maroilles and Landrecies.
Though the night was very dark there was no confusion, as the men
poured hurriedly out from their billets to fall in. Some were at once
detailed to build emergency barricades in the streets, and as the tool
limbers were taken for this purpose the Battalion never had any
heavy tools for the rest of the retreat. The houses on the front of
the town were rapidly put in a state of defence; loopholes were
made, and the furniture, or anything handy, was pushed up to make
the walls bullet-proof.
As it turned out, the enterprise of a small patrol of Uhlans, who rode
unopposed into the town during the afternoon, had proved a very
fortunate thing for the defenders. For it seems to have been
assumed at first that the town was covered by troops from other
brigades, and when the 3rd Battalion Coldstream was ordered to
furnish outposts it had been considered a quite unnecessary
precaution. After the Uhlan incursion, even the most optimistic could
hardly have needed convincing.
When all the dispositions had been made the 2nd Battalion
Grenadiers was distributed as follows: Nos. 2 and 3 Companies,
under the command of Major Lord Bernard Lennox and Captain
Stephen, held the level-crossing over the railway, and watched the
right and left flanks of the road leading over the Sambre. No. 1
Company, under Major Hamilton, held the two sides on the left,
while No. 4 Company, under Captain Colston, in reserve, was posted
on the bridge over the Sambre.
The first warning that the enemy was at hand was given at 8 P.M. by
the firing of the picquets. When the alarm went there was still
sufficient light for the men to get into their positions, but soon after
it became pitch dark, and the rain began to fall. Suddenly shadowy
forms were observed by the outposts moving in the darkness.
Evidently they realised that they had been seen, for a voice was
heard calling out, "Don't shoot. We are the French." The trick at that
time was new to us. Our men naturally hesitated at first to fire, and
this gave the Germans their opportunity for a forward rush.
Very critical moments followed. The two forces were only a short
distance apart, and in the darkness a retreat would have been fatal,
but the splendid discipline of the Guards saved the situation.
Everywhere the attacking Germans found themselves beating up
against a wall of stubborn resistance. They brought up a couple of
guns and poured shells into the town at almost point-blank range;
they even fired case-shot down the road. Again and again they
charged, only to be met and mowed down by a withering fire. The
machine-guns of the Grenadiers were moved up to help the
Coldstream, and came into action at a very critical moment. They
were largely instrumental in repelling the enemy's attack, and were
well handled by Lieutenant the Hon. W. Cecil, who was slightly
wounded. Private Rule particularly distinguished himself by sticking
to his gun and continuing to fight it, although he had been blown off
his feet by the blast of a H.E. shell. The brunt of the attack was
borne at the start by the 3rd Battalion Coldstream, which lost heavily
in this fight; but in the Grenadiers the casualties were not great.
Soon burning houses were lighting up the battlefield, and it began to
be possible to distinguish friend from foe. During one of the bursts
of firing Lieutenant Vereker was hit, and fell shot through the head.
After the first heavy attacks had been repulsed, the enemy tried to
get round the left of the Coldstream in the direction of the railway-
station, but there was met by a steady fire from No. 2 Company,
under Major Lord Bernard Lennox, and could make no headway.
Splendid work was done by a field howitzer, which had been
manhandled up to the level-crossing, and which succeeded in
silencing the enemy's guns.
Sketch plan of Landrecies.
Finally, about midnight, the enemy evidently realised the futility of
going on with the attack, and retreated once more into the
Aug. 26.
darkness. But spasmodic firing continued for some time, and it was
not until nearly 2 A.M. that the night became still, and the men were
able to strengthen their position. It was afterwards learnt that the
Germans who took part in the attack had been pushed up to
Landrecies in two hundred motor lorries. How severely they had
been handled may be surmised from the fact that they allowed the
Grenadiers and 3rd Battalion Coldstream to retire unmolested over a
single bridge across the Sambre. Writing of this engagement in his
despatch of September 7, Sir John French said:
The 4th Guards Brigade in Landrecies was heavily attacked by troops of the
Ninth German Army Corps, who were coming through the forest on the north
of the town. This brigade fought most gallantly and caused the enemy to
suffer tremendous loss in issuing from the forest into the narrow streets of
the town. This loss has been estimated from reliable sources at from 700 to
1000.
In the meantime the Second Corps was between Le Cateau and
Caudry with the 19th Brigade, which had been brought up from the
lines of communication on the left and the Fourth Division south of
Cambrai. The German First Army launched a serious attack along the
whole of this line, and Sir H. Smith-Dorrien, finding himself
outnumbered and out-gunned, had the greatest difficulty in breaking
off the engagement and continuing the retirement.
At daybreak the 4th Brigade again got
orders to retire, and marched unmolested
to Etreux. Unfortunately many of the men had no time to retrieve
their kits, which they had left at their billets, and all these were left
behind. The troops were dead beat, having again had practically no
sleep after a long day's marching and fighting. Every time a halt was
made the whole Battalion fell fast asleep, and when the march had
to be resumed it was very hard to rouse the men. It might seem
hardly worth while to sleep during a brief halt of only a few minutes,
with the prospect of a painful reawakening to the realities of the
situation as the inevitable sequel. But most of the men were so
thoroughly worn out that they eagerly welcomed even the doubtful
blessing of such a respite. In the distance heavy firing could be
Aug. 27.
Aug. 28.
Aug. 29.
heard in the direction of Le Cateau, and at one time it seemed
probable the 4th Brigade might be sent off to support the hard-
pressed Second Corps.
Etreux was reached at last, and the Battalion proceeded to dig itself
in. During the afternoon a German aeroplane flew very low over the
bivouac, and dropped a bomb, which, however, did no damage.
Every one who had a rifle handy had a shot at the unwelcome
visitor; eventually it was forced down a mile away, where it was
picked up by the cavalry. In it were found three officers, two dead
and one wounded.
Another long dusty march lay before the
Brigade on the following day. Continuing
the retirement, it passed through Vénérolles, Tupigny, Vadencourt,
and Hauteville to Mont d'Origny. A report was brought in that a large
force of the enemy had been seen near St. Quentin, but this proved
to be inaccurate. That night the First Corps was in a most critical
position. The Germans had nearly surrounded them, and urgent
orders to entrench the high ground north and east of Mont d'Origny
were received; but although the weary troops dug on till midnight,
nothing occurred, and at 3.30 A.M. the Battalion started off again.
It reached Deuillet near La Fère, where it
had the only day's halt during the retreat.
On the way the Scots Greys and 12th Lancers charged a large force
of German cavalry and utterly routed them, making many prisoners,
but otherwise nothing was seen of the enemy.
On arrival at Deuillet, the usual procedure was gone through, and a
position in defence was entrenched, the men working at it all day.
In the evening an electrifying report, which
cheered every one up, went round that
there was to be a general advance. But when the order came it was
the usual one to retire, and another hot march of twenty-eight miles
followed. The weary, wearing ordeal of long day marches and but
little sleep had commenced again. As soon as it was decided to
Aug. 30-31.
Sept. 1. Villers-
Cotterêts.
continue the retreat, and the whole British Force had crossed over
the Oise, the bridges were blown up. The heat was intense. There
was practically no wind, and the dust was stifling; a very large
number of men were suffering from sore feet, and there was a good
deal of grumbling in the ranks at the endless marching in the wrong
direction. But there was no prospect of a long rest, and those
battalions which were unlucky enough to leave men behind never
saw them again. Not a man from the 2nd Grenadiers, however, fell
out.
The two corps which had been dangerously separated were now
once more united, but the pursuing Germans were very near, and
the situation still gave rise to much anxiety. Information was
received to the effect that five or six German corps were pursuing
the Fifth French Army, while at least two corps were advancing on
the British Army. The situation on the left of the British Army was
obscure, but it was reported that the enemy had three or four more
corps endeavouring to creep round that flank. In response to Sir
John French's representations, General Joffre ordered the Fifth
French Army to attack the enemy on the Somme with the object of
relieving the pressure on the British Army.
The Battalion reached Soissons about
midday on the 30th, and was ordered to
occupy the ridge near Pasly, about two miles north of the town. Next
day it tramped on to Soucy, a very hard march in great heat,
finishing up with a steep climb. Here it bivouacked as usual, and
snatched what rest it could. But a full night's sleep was always out of
the question, and soon after midnight the whole Brigade was
directed to form a rearguard, to cover the retirement of the Second
Division.
Accordingly trenches were dug in the high
ground above Soucy, No. 4 Company
Grenadiers being detached to guard the right flank in a position
leading across a deep ravine to the high ground above Montgobert.
It was to rejoin the Battalion when it retired to the forest of Villers-
Cotterêts. Soon after the Germans came in sight, and retirement
from the first position was successfully effected. The 2nd Battalion
Grenadiers and 3rd Battalion Coldstream made their way into the
wood, the edges of which were held by the Irish Guards and 2nd
Battalion Coldstream, and took up a fresh position along the line of
the main road running east and west through Rond de la Reine.
Thick mist hung over the country, and the dense undergrowth made
the passage of the wood difficult. The Germans, it was assumed,
would not attempt to penetrate the wood, but would be content to
use the roads and drives. The assumption proved to be wrong—
fortunately for us. As it happened, they came through the very
thickest part, and in so doing lost cohesion and direction. Probably,
in fact, it was their doing this, and the confusion into which they
were consequently thrown, that enabled the 4th Brigade to break off
the action later in the evening and retire unmolested.
The 2nd Battalion Grenadiers held the right of the line. From a
strategic point of view, the position it occupied could not well have
been worse. But in a rearguard action there is often no choice. It
was absolutely necessary to retard the advance of the enemy
through the wood, so that the rest of the Division should get away.
During the time of waiting for the oncoming Germans, the Scots
Greys and 12th Lancers suddenly appeared, coming down the ride
on the right. They had been attracted by the firing, and came to see
what was going on. They dismounted, and, finding many friends
among the Grenadiers, started "coffee-housing" for a while. But the
firing in the outskirts of the wood began to sound serious, and they
rode off along the road to the left, with the idea of operating against
the enemy's right.
A few minutes later the Germans appeared, and a fight at close
quarters began. The firing became very hot, as in some places the
opposing forces were hardly seventy yards apart. Good work was
done by the machine-guns of the Grenadiers and Irish Guards, which
accounted for a large number of Germans, while the men charged
repeatedly with the bayonet and drove the enemy back. Gallantly,
stolidly, the 4th Brigade held on until the order came to retire.
Even with highly-disciplined troops, a rear-guard action in a wood is
one of the most difficult manoeuvres to carry out well. It is quite
impossible for the commanding officer to keep a firm grip of his
battalion when it is scattered about in different rides; orders passed
along often do not reach all the platoons, and men of different
companies, and even regiments, are wont to get hopelessly mixed.
Fortunately in the Brigade of Guards the men are all trained on the
same system, and, except for some small characteristic differences,
a man belonging to one regiment will be quite at home in any of the
others.
At Villers-Cotterêts the men of the 4th Brigade became very much
mixed, and officers took command of the men who happened to be
near them. The wood, too, was so thick that at fifty yards' distance
parties were practically out of sight of each other. One result of this
difficulty of keeping in touch was that two platoons of No. 4
Company never got the order to retire.
Engagement at Villers-Cotterêts. September 1.
1914.
These two platoons, under the command of Lieutenant the Hon. F.
E. Needham and Lieutenant the Hon. J. N. Manners, were at the
Cross Roads at Rond de la Reine. As the Germans came on,
Brigadier-General Scott-Kerr, finding that they were creeping round
his left flank, ordered these two platoons down a ride to the left, to
enfilade them. Making the best dispositions they could, these two
officers continued to fight, when they suddenly realised that they
were cut off and the Germans were on all sides of them. True to the
traditions of the Regiment, they stuck to their posts, and fought on
till all were killed or wounded.
Lieutenant the Hon. J. N. Manners was killed while directing the fire
of his platoon, and Lieutenant the Hon. F. Needham, badly wounded,
was taken prisoner. Lieutenant G. E. Cecil, another officer belonging
to these platoons, seeing the Germans streaming across a ride to his
left, dashed off with some men to stop them. He had not gone far
before he was shot through the hand; stumbling forward, he
recovered his feet, and, drawing his sword, he called on the men to
charge when a bullet struck him in the head. And there were other
casualties among the officers. Earlier in the day the Adjutant of the
Battalion, Lieutenant I. MacDougall, was shot dead while carrying
orders to the firing-line. His place was taken by Captain E. J. L. Pike.
The Brigadier-General, Scott-Kerr, who rode up to give some orders,
was badly wounded in the thigh, and the command of the Brigade
passed to Colonel Corry, while Major Jeffreys took over the 2nd
Battalion Grenadiers. Field-Marshal Sir John French, on hearing of
this, sent the following telegram to Brigadier-General Scott-Kerr, care
of Communications:
My warm congratulations on gallantry of your Brigade A A A am deeply
grieved to hear you are wounded A A A I shall miss your valuable help very
much A A A my best wishes for your recovery.
French.
Captain W. T. Payne-Gallwey, M.V.O., who was in charge of the
machine-guns in the First Brigade, was reported missing.
Orders were given to retire, and the Battalion quietly withdrew in
single file of half-platoons, covered by a rear party from No. 2
Company. The enemy, as already stated, had been thrown into
hopeless confusion in the wood, and, in spite of a prodigious amount
of shouting and blowing of horns, could not get forward. Some three
hours later a second engagement was fought on the other side of
Villers-Cotterêts. The 4th Brigade retired through the 6th Brigade,
which with the field artillery had taken up a position at the edge of
another wood. The enemy's first shells came over as the 4th Brigade
moved into the wood. The British guns succeeded in keeping the
Germans at bay, but were only got away with the utmost difficulty
and some loss.
Having borne the brunt of the fighting, the 4th Brigade had
necessarily suffered heavy casualties.
The 2nd Battalion Grenadiers lost 4 officers and 160 men, while the
Irish Guards lost 4 officers and the Coldstream 7, as well as a large
number of men. Two exceptionally good officers in the Irish Guards
were killed—Colonel the Hon. G. Morris and Major H. F. Crichton.
The latter served in the Grenadiers for some years before
exchanging into the Irish Guards.[1]
On emerging once more into open country, the 2nd Battalion
Grenadiers was sent off to march to Boursonne, which it reached
about 4 P.M. Two companies of the 2nd Battalion Coldstream were
ordered back to support the 6th Brigade, which was now protecting
the retreat of the guns; but they were not wanted after all, and were
sent back to Boursonne after a fruitless journey. Then General Monro
rode up, and ordered the 2nd Battalion Grenadiers to take up a rear-
guard position about Boursonne, to cover the retirement of the 6th
Brigade. Meanwhile, the Brigade Headquarters, the Irish Guards, and
the 3rd Battalion Coldstream went on to Betz.
When the 6th Brigade had passed through, the 2nd Battalion
Grenadiers and 2nd Battalion Coldstream retired to Thury.
Unfortunately no orders had been given them to go to Betz, and
through following the 6th Brigade these two battalions missed the
guide whom Battalion Headquarters had sent to meet them. Once
more the men were absolutely dead beat. They had had nothing to
eat since tea the day before, but when the matter of food was
Sept. 2.
inquired into it was found that all the supplies had gone on to Betz.
This was at 11 o'clock at night, and it looked as if the men would
have to bivouac foodless by the roadside.
Heroic measures were called for, and Major Jeffreys decided to brush
aside the ordinary procedure and shortcircuit the usual channels of
communication by going straight to the Divisional Commander,
General Monro. He was instantly successful. On learning of the sad
plight of the Battalion, General Monro undertook to supply it with
food. He ordered his D.A.Q.M.G. to take the Battalion to his supply
depot, and Major Jeffreys went back and fell in his weary men.
With the promise of a meal ahead they responded gamely, and
marched off to La Villeneuve, the place indicated by the General,
where rations of bully-beef, bread, and cheese were soon
distributed.
Then the men were allowed two hours' sleep by way of a night's rest
after one of the longest and most strenuous days they had ever had.
They were more fortunate, though, than the men of the 2nd
Battalion Coldstream Guards, who did not even manage to get any
food that night, and who had to snatch what sleep they could lying
down in the streets of Thury.
At 2 A.M. the Battalion marched off again—
still retiring—through Antilly to Betz, where
it was joined by No. 1 Company and 45 men of No. 4 under
Lieutenant Stocks. Thence by Montrolle to Reez, where a halt was
made for water, and on to Puisieux. Here the men had a late
breakfast, and then, in stifling heat, continued their march, with
constant halts, through La Chaussée and Barcy to Meaux. They
reached this village at 4 P.M., and, their long day's journey ended,
they were refreshed by a bathe in the Ourcq Canal. This march was
almost the hardest of the whole retreat, but, in spite of everything,
the Battalion marched on, with scarcely a man out of the ranks,
although the number of men who fell out in other regiments was by
no means small.
Sept. 3.
Sept. 4.
Undoubtedly the men were by now beginning to feel the strain of
this interminable retirement. However footsore and weary they may
be, British troops will always respond when called upon to advance.
But to ask them to make a special effort when retreating is quite
another thing, even with the most highly disciplined. Besides, they
were quite unable to see the necessity of it all. There had been no
pitched battle, no defeat—in fact, whenever they had had a chance
they had inflicted enormous losses on the enemy and driven him
back. Of course they had seen no newspapers, and had no way of
picking up any real idea of what was going on in France.
Next morning at 7 o'clock the march was
resumed eastwards, and the Division
crossed the Marne at Trilport, blowing the bridges up after them.
This new direction was the result of the Germans moving along the
north bank of the Marne, which they crossed near Sammeron. Then
the Battalion moved southward again, through Montceaux and Forêt
du Mans to Pierre Levée, where it bivouacked.
The men had expected a rest on September
4, but the order soon arrived for the
Brigade to continue the retirement. No. 3 Company of the 2nd
Battalion Grenadiers under Captain Gosselin, and No. 4 Company
under Captain Symes-Thompson, were sent out on outpost duty.
In the morning the Brigade marched to Les Laquais, where trenches
were dug, joining up with the 5th and 6th Brigades on the right. At 5
P.M. the enemy shelled the right of the line, and at dusk the Brigade
withdrew. It picked up No. 3 Company at Grande Loge Farm, and
marched through Maisoncelles and Rouilly le Fay to Le Bertrand,
where it bivouacked for the night.
Meanwhile Major Lord Bernard Lennox was despatched to
Coulommiers to find the first draft that had been sent out from
home—90 men under Captain Ridley. They arrived about midday
after a train journey of thirty-six hours—they had been all round the
country, constantly receiving fresh orders to go to different places.
Lord Bernard Lennox had been instructed to remain at Coulommiers,
Sept. 5.
Sept. 6.
but when he found the First Division retiring through the town all the
afternoon, he decided to strike off westward with the new draft in
search of the Battalion. This plan succeeded, and he found it about
midnight.
It was a sadly tattered, unshaven, footsore
body of men that marched at 3 o'clock next
morning through La Celle and Malmaison Farm to Fontenay, where
they went into billets. No Londoner seeing them would have guessed
that these were the same smart Grenadiers whom he had often
admired on the King's Guard. But if their looks were gone, their spirit
was indomitable as ever.
The Germans seem to have been genuinely under the delusion that
by this time the long retreat had reduced the British Army, always
"contemptible," to a mere spiritless mob, which it was no longer
necessary to take into calculation in developing their plan of
campaign. They little knew the British soldier. So far the 2nd
Battalion Grenadiers had had no chance of showing its quality; it had
just been marched off its feet from the start—in the wrong direction.
But, in spite of all the men had gone through, they were ready at
any moment to turn and fight like lions when they were allowed to.
And now at last the moment was close at
hand. To their joyful surprise the officers of
the Battalion found, on the morning of September 6, that the
direction had been changed, and that an advance was to be made
eastward against the German flank. At first it was thought that this
meant the beginning of an offensive-defensive, the German attack
having failed; but in reality, of course, the change was a much
bigger one even than this. The French reserves were now available,
and the Germans' greatest asset, superior numbers, was lost to
them. And so a new phase of the campaign began to develop.
On the 6th Lieut.-Colonel Corry resumed the command of the
Battalion, and Lieut.-Colonel G. Feilding took command of the
Brigade.
CHAPTER IV
THE BATTLE OF THE MARNE (2ND BATTALION)
The German General Staff at this juncture realised that a retreating
army is not necessarily a beaten one. For the last ten days, with
their maps spread before them, they had had the satisfaction of
moving the pins and flags representing their forces continually and
rapidly nearer and nearer Paris. But if the French Army—the British
Army, they thought, could be safely ignored—were to succeed in
escaping south, it would remain a constant menace. It might even
interfere with the Emperor's spectacular entry into Paris, every detail
of which had been sketched out beforehand by the officials, whose
business it was to stage-manage all the theatrical pageantry of their
Imperial master's movements.
So a big coup was wanted—a smashing blow at the French. If the
centre of the French line could be pierced by the combined efforts of
Von Hausen's, the Duke of Würtemberg's, and the Crown Prince's
armies, and if simultaneously Von Kluck's army, which had reached
Senlis, and was only twenty-five miles from Paris, could execute a
swift movement to the south-east, the Fifth French Army would be
caught in a vice. This strategic plan really menaced the whole of the
interior of France, and had it succeeded might have resulted in her
downfall. In all these calculations of the German Staff it appears to
have been assumed that the British Army was practically out of
action, and that whatever remained of it had in all probability been
sent to reinforce the weak spot at Bar-le-Duc.
To accomplish his decisive stroke, Von Kluck had to execute that
most dangerous of all manoeuvres, a flank march with the object of
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com

More Related Content

PDF
C 20 for Programmers 3rd Edition P. Deitel
PDF
C 20 for Programmers 3rd Edition P. Deitel
PDF
C 20 for Programmers 3rd Edition P. Deitel
PDF
C 20 for Programmers 3rd Edition Harvey Deitel
PDF
Starting Out With C Early Objects 7th Edition 7th Edition Tony Gaddis
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PDF
(eBook PDF) C++ How to Program 10th Edition by Paul J. Deitel
PDF
Programming c++
C 20 for Programmers 3rd Edition P. Deitel
C 20 for Programmers 3rd Edition P. Deitel
C 20 for Programmers 3rd Edition P. Deitel
C 20 for Programmers 3rd Edition Harvey Deitel
Starting Out With C Early Objects 7th Edition 7th Edition Tony Gaddis
C++ How to Program 10th Edition Deitel Solutions Manual
(eBook PDF) C++ How to Program 10th Edition by Paul J. Deitel
Programming c++

Similar to C 20 for Programmers 3rd Edition P. Deitel (20)

PDF
(eBook PDF) C++ How to Program 10th Edition by Paul J. Deitel
PPT
programming week 2.ppt
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
Download full ebook of Programming in C 2nd Edition Safari instant download pdf
PDF
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
PPT
Basics of c++ Programming Language
PDF
(eBook PDF) Starting Out with C++: From Control Structures through Objects, B...
PDF
Starting out with C from control structures through objects Eighth Edition To...
PDF
PDF
Programming in C 2nd Edition Safari download pdf
PDF
Introduction to c++
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
PPTX
introductiontocprogramming datatypespp.pptx
PDF
Starting out with C from control structures through objects Eighth Edition To...
PDF
Starting out with C from control structures through objects Eighth Edition To...
(eBook PDF) C++ How to Program 10th Edition by Paul J. Deitel
programming week 2.ppt
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
Download full ebook of Programming in C 2nd Edition Safari instant download pdf
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
Basics of c++ Programming Language
(eBook PDF) Starting Out with C++: From Control Structures through Objects, B...
Starting out with C from control structures through objects Eighth Edition To...
Programming in C 2nd Edition Safari download pdf
Introduction to c++
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
introductiontocprogramming datatypespp.pptx
Starting out with C from control structures through objects Eighth Edition To...
Starting out with C from control structures through objects Eighth Edition To...
Ad

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
01-Introduction-to-Information-Management.pdf
PPTX
master seminar digital applications in india
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
Lesson notes of climatology university.
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
VCE English Exam - Section C Student Revision Booklet
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Sports Quiz easy sports quiz sports quiz
Anesthesia in Laparoscopic Surgery in India
Module 4: Burden of Disease Tutorial Slides S2 2025
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
01-Introduction-to-Information-Management.pdf
master seminar digital applications in india
102 student loan defaulters named and shamed – Is someone you know on the list?
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Supply Chain Operations Speaking Notes -ICLT Program
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Structure & Organelles in detailed.
Lesson notes of climatology university.
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Ad

C 20 for Programmers 3rd Edition P. Deitel

  • 1. Get the full ebook with Bonus Features for a Better Reading Experience on ebookgate.com C 20 for Programmers 3rd Edition P. Deitel https://ebookgate.com/product/c-20-for-programmers-3rd- edition-p-deitel/ OR CLICK HERE DOWLOAD NOW Download more ebook instantly today at https://ebookgate.com
  • 2. Instant digital products (PDF, ePub, MOBI) available Download now and explore formats that suit you... JavaScript for Programmers 1st Edition Paul J. Deitel https://ebookgate.com/product/javascript-for-programmers-1st-edition- paul-j-deitel/ ebookgate.com C for Java Programmers 1st Edition Harold Cabrera https://ebookgate.com/product/c-for-java-programmers-1st-edition- harold-cabrera/ ebookgate.com C for Java Programmers 1st Edition Dario Laverde https://ebookgate.com/product/c-for-java-programmers-1st-edition- dario-laverde/ ebookgate.com C How to Program 6th Edition Paul Deitel https://ebookgate.com/product/c-how-to-program-6th-edition-paul- deitel/ ebookgate.com
  • 3. C How to Program 9e 9th Edition Paul Deitel https://ebookgate.com/product/c-how-to-program-9e-9th-edition-paul- deitel/ ebookgate.com C How to Program 7th Edition Paul J. Deitel https://ebookgate.com/product/c-how-to-program-7th-edition-paul-j- deitel/ ebookgate.com C How to Program Fourth Edition Harvey M. Deitel https://ebookgate.com/product/c-how-to-program-fourth-edition-harvey- m-deitel/ ebookgate.com Internet World Wide Web How to Program Fourth Edition P. J. Deitel https://ebookgate.com/product/internet-world-wide-web-how-to-program- fourth-edition-p-j-deitel/ ebookgate.com Herding Cats A Primer for Programmers Who Lead Programmers 1st Edition J. Hank Rainwater https://ebookgate.com/product/herding-cats-a-primer-for-programmers- who-lead-programmers-1st-edition-j-hank-rainwater/ ebookgate.com
  • 6. Deitel® Developer Series C++ 20 for Programmers Paul Deitel • Harvey Deitel
  • 7. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. Copyright © 2021 Pearson Education, Inc. All rights reserved. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, request forms and the appropriate contacts within the Pearson Education Global Rights & Permissions Department, please visit www.pearson.com/permissions. ISBN-13: 978-0-13-690569-1 ISBN-10: 0-13-690569-1
  • 8. Contents Preface Part 1: C++ Fundamentals Quickstart Chapter 1. Introduction and Test-Driving a C++ Application Chapter 2. Introduction to C++ Programming Chapter 3. Control Statements, Part 1; Intro to C++20 Text Formatting Chapter 4. Control Statements, Part 2 Chapter 5. Functions Part 2: Arrays, Pointers, Strings and Files Chapter 6. arrays, vectors, C++20 Ranges and Functional- Style Programming Chapter 7. (Downplaying) Pointers in Modern C++ Chapter 8. strings, string_views, Text Files, CSV Files and Regex Part 3: Object-Oriented Programming Chapter 9. Custom Classes Chapter 10. OOP: Inheritance and Runtime Polymorphism Chapter 11. Operator Overloading, Copy/Move Semantics and Smart Pointers Chapter 12. Exceptions and a Look Forward to Contracts Part 4: Standard Library Containers, Iterators and Algorithms Chapter 13. Standard Library Containers and Iterators Chapter 14. Standard Library Algorithms and C++20 Ranges & Views Part 5: Advanced Topics Chapter 15. Templates, C++20 Concepts and Metaprogramming Chapter 16. C++20 Modules: Large-Scale Development
  • 9. Chapter 17. Concurrent Programming; Intro to C++20 Coroutines Part 6: Other Topics Chapter 18. Stream I/O; C++20 Text Formatting: A Deeper Look Chapter 19. Other Topics; A Look Toward C++23 and Contracts Part 7: Appendices Appendix A: Operator Precedence and Grouping Appendix B: Character Set Appendix C: Fundamental Types Appendix D: Number Systems Appendix E: Preprocessor Appendix F: Bits, Characters, C Strings and structs Appendix G: C Legacy Code Topics Appendix H: Using the Visual Studio Debugger Appendix I: Using the GNU C++ Debugger Appendix J: Using the Xcode Debugger
  • 10. Table of Contents Preface Part 1: C++ Fundamentals Quickstart Chapter 1. Introduction and Test-Driving a C++ Application 1.1 Introduction 1.2 Test-Driving a C++20 Application Chapter 2. Introduction to C++ Programming 2.1 Introduction 2.2 First Program in C++: Displaying a Line of Text 2.3 Modifying Our First C++ Program 2.4 Another C++ Program: Adding Integers 2.5 Arithmetic 2.6 Decision Making: Equality and Relational Operators 2.7 Objects Natural: Creating and Using Objects of Standard Library Class string 2.8 Wrap-Up Chapter 3. Control Statements, Part 1; Intro to C++20 Text Formatting 3.1 Introduction 3.2 Control Structures 3.3 if Single-Selection Statement 3.4 if…else Double-Selection Statement 3.5 while Iteration Statement 3.6 Counter-Controlled Iteration 3.7 Sentinel-Controlled Iteration 3.8 Nested Control Statements 3.9 Compound Assignment Operators 3.10 Increment and Decrement Operators
  • 11. 3.11 Fundamental Types Are Not Portable 3.12 Objects Natural Case Study: Arbitrary Sized Integers 3.13 C++20 Feature Mock-Up—Text Formatting with Function format 3.14 Wrap-Up Chapter 4. Control Statements, Part 2 4.1 Introduction 4.2 Essentials of Counter-Controlled Iteration 4.3 for Iteration Statement 4.4 Examples Using the for Statement 4.5 Application: Summing Even Integers 4.6 Application: Compound-Interest Calculations 4.7 do…while Iteration Statement 4.8 switch Multiple-Selection Statement 4.9 C++17: Selection Statements with Initializers 4.10 break and continue Statements 4.11 Logical Operators 4.12 Confusing the Equality (==) and Assignment (=) Operators 4.13 C++20 Feature Mock-Up: [[likely]] and [[unlikely]] Attributes 4.14 Objects Natural Case Study: Using the miniz-cpp Library to Write and Read ZIP files 4.15 C++20 Feature Mock-Up: Text Formatting with Field Widths and Precisions 4.16 Wrap-Up Chapter 5. Functions 5.1 Introduction 5.2 Program Components in C++ 5.3 Math Library Functions 5.4 Function Definitions and Function Prototypes 5.5 Order of Evaluation of a Function’s Arguments 5.6 Function-Prototype and Argument-Coercion Notes
  • 12. 5.7 C++ Standard Library Headers 5.8 Case Study: Random-Number Generation 5.9 Case Study: Game of Chance; Introducing Scoped enums 5.10 C++11’s More Secure Nondeterministic Random Numbers 5.11 Scope Rules 5.12 Inline Functions 5.13 References and Reference Parameters 5.14 Default Arguments 5.15 Unary Scope Resolution Operator 5.16 Function Overloading 5.17 Function Templates 5.18 Recursion 5.19 Example Using Recursion: Fibonacci Series 5.20 Recursion vs. Iteration 5.21 C++17 and C++20: [[nodiscard]] Attribute 5.22 Lnfylun Lhqtomh Wjtz Qarcv: Qjwazkrplm xzz Xndmwwqhlz 5.23 Wrap-Up Part 2: Arrays, Pointers, Strings and Files Chapter 6. arrays, vectors, C++20 Ranges and Functional- Style Programming 6.1 Introduction 6.2 arrays 6.3 Declaring arrays 6.4 Initializing array Elements in a Loop 6.5 Initializing an array with an Initializer List 6.6 C++1 1 Range-Based for and C++20 Range-Based for with Initializer 6.7 Setting array Elements with Calculations; Introducing constexpr 6.8 Totaling array Elements 6.9 Using a Primitive Bar Chart to Display array Data
  • 13. Graphically 6.10 Using array Elements as Counters 6.11 Using arrays to Summarize Survey Results 6.12 Sorting and Searching arrays 6.13 Multidimensional arrays 6.14 Intro to Functional-Style Programming 6.15 Objects Natural Case Study: C++ Standard Library Class Template vector 6.16 Wrap-Up Chapter 7. (Downplaying) Pointers in Modern C++ 7.1 Introduction 7.2 Pointer Variable Declarations and Initialization 7.3 Pointer Operators 7.4 Pass-by-Reference with Pointers 7.5 Built-In Arrays 7.6 C++20: Using to_array to convert a Built-in Array to a std::array 7.7 Using const with Pointers and the Data They Point To 7.8 sizeof Operator 7.9 Pointer Expressions and Pointer Arithmetic 7.10 Objects Natural Case Study: C++20 spans—Views of Contiguous Container Elements 7.11 A Brief Intro to Pointer-Based Strings 7.12 Looking Ahead to Other Pointer Topics 7.13 Wrap-Up Chapter 8. strings, string_views, Text Files, CSV Files and Regex 8.1 Introduction 8.2 string Assignment and Concatenation 8.3 Comparing strings 8.4 Substrings 8.5 Swapping strings 8.6 string Characteristics
  • 14. 8.7 Finding Substrings and Characters in a string 8.8 Replacing Characters in a string 8.9 Inserting Characters into a string 8.10 C++11 Numeric Conversions 8.11 C++17 string_view 8.12 Files and Streams 8.13 Creating a Sequential File 8.14 Reading Data from a Sequential File 8.15 C++14 Reading and Writing Quoted Text 8.16 Updating Sequential Files 8.17 String Stream Processing 8.18 Raw String Literals 8.19 Objects Natural Case Study: Reading and Analyzing a CSV File Containing Titanic Disaster Data 8.20 Objects Natural Case Study: Introduction to Regular Expressions 8.21 Wrap-Up Part 3: Object-Oriented Programming Chapter 9. Custom Classes 9.1 Introduction 9.2 Test-Driving an Account Object 9.3 Account Class with a Data Member and Set and Get Member Functions 9.4 Account Class: Custom Constructors 9.5 Software Engineering with Set and Get Member Functions 9.6 Account Class with a Balance 9.7 Time Class Case Study: Separating Interface from Implementation 9.8 Compilation and Linking Process 9.9 Class Scope and Accessing Class Members 9.10 Access Functions and Utility Functions 9.11 Time Class Case Study: Constructors with Default Arguments
  • 15. 9.12 Destructors 9.13 When Constructors and Destructors Are Called 9.14 Time Class Case Study: A Subtle Trap—Returning a Reference or a Pointer to a private Data Member 9.15 Default Assignment Operator 9.16 const Objects and const Member Functions 9.17 Composition: Objects as Members of Classes 9.18 friend Functions and friend Classes 9.19 The this Pointer 9.20 static Class Members—Classwide Data and Member Functions 9.21 Aggregates in C++20 9.22 Objects Natural Case Study: Serialization with JSON 9.23 Wrap-Up Chapter 10. OOP: Inheritance and Runtime Polymorphism 10.1 Introduction 10.2 Base Classes and Derived Classes 10.3 Relationship between Base and Derived Classes 10.4 Constructors and Destructors in Derived Classes 10.5 Intro to Runtime Polymorphism: Polymorphic Video Game 10.6 Relationships Among Objects in an Inheritance Hierarchy 10.7 Virtual Functions and Virtual Destructors 10.8 Abstract Classes and Pure virtual Functions 10.9 Case Study: Payroll System Using Runtime Polymorphism 10.10 Runtime Polymorphism, Virtual Functions and Dynamic Binding “Under the Hood” 10.11 Non-Virtual Interface (NVI) Idiom 10.12 Program to an Interface, Not an Implementation 10.13 Runtime Polymorphism with std::variant and std::visit 10.14 Multiple Inheritance 10.15 protected Class Members
  • 16. 10.16 public, protected and private Inheritance 10.17 Wrap-Up Chapter 11. Operator Overloading, Copy/Move Semantics and Smart Pointers 11.1 Introduction 11.2 Using the Overloaded Operators of Standard Library Class string 11.3 Operator Overloading Fundamentals 11.4 (Downplaying) Dynamic Memory Management with new and delete 11.5 Modern C++ Dynamic Memory Management—RAII and Smart Pointers 11.6 MyArray Case Study: Crafting a Valuable Class with Operator Overloading 11.7 C++20 Three-Way Comparison Operator (<=>) 11.8 Converting Between Types 11.9 explicit Constructors and Conversion Operators 11.10 Overloading the Function Call Operator () 11.11 Wrap-Up Chapter 12. Exceptions and a Look Forward to Contracts 12.1 Introduction 12.2 Exception-Handling Flow of Control; Defining an Exception Class 12.3 Exception Safety Guarantees and noexcept 12.4 Rethrowing an Exception 12.5 Stack Unwinding and Uncaught Exceptions 12.6 When to Use Exception Handling 12.7 Constructors, Destructors and Exception Handling 12.8 Processing new Failures 12.9 Standard Library Exception Hierarchy 12.10 C++’s Alternative to the finally Block 12.11 Libraries Often Support Both Exceptions and Error Codes
  • 17. 12.12 Logging 12.13 Looking Ahead to Contracts 12.14 Wrap-Up Part 4: Standard Library Containers, Iterators and Algorithms Chapter 13. Standard Library Containers and Iterators 13.1 Introduction 13.2 Introduction to Containers 13.3 Working with Iterators 13.4 A Brief Introduction to Algorithms 13.5 Sequence Containers 13.6 vector Sequence Container 13.7 list Sequence Container 13.8 deque Sequence Container 13.9 Associative Containers 13.10 Container Adaptors 13.11 bitset Near Container 13.12 Optional: A Brief Intro to Big O 13.13 Optional: A Brief Intro to Hash Tables 13.14 Wrap-Up Chapter 14. Standard Library Algorithms and C++20 Ranges & Views 14.1 Introduction 14.2 Algorithm Requirements: C++20 Concepts 14.3 Lambdas and Algorithms 14.4 Algorithms 14.5 Function Objects (Functors) 14.6 Projections 14.7 C++20 Views and Functional-Style Programming 14.8 Intro to Parallel Algorithms 14.9 Standard Library Algorithm Summary 14.10 A Look Ahead to C++23 Ranges 14.11 Wrap-Up
  • 18. Part 5: Advanced Topics Chapter 15. Templates, C++20 Concepts and Metaprogramming 15.1 Introduction 15.2 Custom Class Templates and Compile-Time Polymorphism 15.3 C++20 Function Template Enhancements 15.4 C++20 Concepts: A First Look 15.5 Type Traits 15.6 C++20 Concepts: A Deeper Look 15.7 Testing C++20 Concepts with static_assert 15.8 Creating a Custom Algorithm 15.9 Creating a Custom Container and Iterators 15.10 Default Arguments for Template Type Parameters 15.11 Variable Templates 15.12 Variadic Templates and Fold Expressions 15.13 Template Metaprogramming 15.14 Wrap-Up Chapter 16. C++20 Modules: Large-Scale Development 16.1 Introduction 16.2 Compilation and Linking Prior to C++20 16.3 Advantages and Goals of Modules 16.4 Example: Transitioning to Modules—Header Units 16.5 Example: Creating and Using a Module 16.6 Global Module Fragment 16.7 Separating Interface from Implementation 16.8 Partitions 16.9 Additional Modules Examples 16.10 Modules Can Reduce Translation Unit Sizes and Compilation Times 16.11 Migrating Code to Modules 16.12 Future of Modules and Modules Tooling 16.13 Wrap-Up Chapter 17. Concurrent Programming; Intro to C++20
  • 19. Coroutines Part 6: Other Topics Chapter 18. Stream I/O; C++20 Text Formatting: A Deeper Look Chapter 19. Other Topics; A Look Toward C++23 and Contracts Part 7: Appendices Appendix A: Operator Precedence and Grouping Appendix B: Character Set Appendix C: Fundamental Types Appendix D: Number Systems Appendix E: Preprocessor Appendix F: Bits, Characters, C Strings and structs Appendix G: C Legacy Code Topics Appendix H: Using the Visual Studio Debugger Appendix I: Using the GNU C++ Debugger Appendix J: Using the Xcode Debugger
  • 20. Preface Welcome to the C++ programming language and C++20 for Programmers. This book presents leading-edge computing technologies for software developers. These are exciting times in the programming-languages community with each of the major languages striving to keep pace with compelling new programming technologies. The ISO C++ Standards Committee now releases a new standard every three years and the compiler vendors implement the new features promptly. C++20 for Programmers is based on the new C++20 standard. Live-Code Approach At the heart of the book is the Deitel signature live-code approach. We present most concepts in the context of complete working programs followed by one or more sample executions. Read the Before You Begin section that follows this Preface to learn how to set up your Windows, macOS or Linux computer to run the hundreds of code examples. All the source code is available at https://www.deitel.com/c-plus-plus-20-for-programmers We recommend that you compile and run each program as you study it. “Rough-Cut” E-Book for O’Reilly Online Learning Subscribers You are viewing an early-access “rough cut” of C++20 for Programmers. We prepared this content carefully, but it has not yet been reviewed or copy edited and is subject to change. As we complete each chapter, we’ll post it here. Please send any corrections, comments, questions and suggestions for improvement to paul@deitel.com and I’ll respond promptly. Check here frequently for updates. “Sneak Peek” Videos for O’Reilly Online Learning Subscribers
  • 21. As an O’Reilly Online Learning subscriber, you also have access to the “sneak peek” of our new C++20 Fundamentals LiveLessons videos at: https://learning.oreilly.com/videos/c-20-fundamentals-part Co-author Paul Deitel immediately records each video lesson as we complete each rough-cut e-book chapter. Lessons go live on O’Reilly Online Learning a few days later. Again, check here frequently for updates. Modern C++ 20 The C++ programming language is popular for developing systems software, embedded systems, operating systems, real-time systems, computer games, communications systems and other high-performance computer applications. C++20 for Programmers is an introductory-through- intermediate-level, professional tutorial presentation of C++. The book is not a full-language reference manual, nor is it a “cookbook.” We focus on Modern C++, which consists of the four most recent C++ standards—C++11, C++14, C++17 and C++20. Throughout the book, features from these standards are marked with icons in the margins like the 20 icon shown here. Compilers We tested every program in the book on three popular free compilers: • Visual C++ in Microsoft Visual Studio Community edition on Windows, • Clang in Xcode on macOS, and • GNU C++ on Linux and in the GNU Compiler Collection (GCC) Docker container. At the time of this writing, some C++20 features are fully implemented in all three compilers, some are implemented in a subset of the three and some are not implemented at all. We point out these issues as appropriate and will update our online content as the compiler vendors implement the rest of C++20’s features. C++20 compiler support for many more compilers is tracked at https://en.cppreference.com/w/cpp/compiler_support
  • 22. We’ll also post updates on the book’s website at https://deitel.com/books/c-plus-plus-20-for-programmers Target Audiences C++20 for Programmers and our C++20 Fundamentals LiveLessons videos have several target audiences: • Non-C++ software developers who are about to do a C++ project and want to learn the latest version of the language, C++20, in the context of a professional-style, language tutorial. • Software developers who may have learned C++ in college or used it professionally some time ago and want to refresh their C++ knowledge in the context of C++20. • C++ software developers who want to learn C++20 in the context of a professional-style, language tutorial. PERF Security Focus on Performance and Security Issues Throughout the book, we call your attention to performance and security issues with the icons you see here in the margin. “Objects Natural” Learning Approach In your C++ programs, you’ll create and use many objects of carefully- developed-and-tested preexisting classes that enable you to perform significant tasks with minimal code. These classes typically come from: • the C++ Standard Library, • platform-specific libraries, such as those provided by Microsoft Windows, Apple macOS or various Linux versions, • free third-party C++ libraries, often created by the open-source community, and • libraries created by fellow developers, such as those in your organization. To help you appreciate this style of programming, early in the book you’ll create and use objects of preexisting classes before creating your own custom
  • 23. classes in later chapters. We call this the “objects natural” approach. Our “Objects Natural” Learning Approach evolved organically as we worked on our Python for Programmers book (https://learning.oreilly.com/library/view/python- for-programmers/9780135231364/) and our Python Fundamentals LiveLessons videos (https://learning.oreilly.com/videos/python- fundamentals/9780135917411), but C++20 for Programmers is the first book in which we’re using the term, “Objects Natural.” “Rough-Cut” Table of Contents (Subject to Change) Part 1: C++ Fundamentals Quickstart 1. Introduction and Test-Driving a C++ Application 2. Introduction to C++ Programming 3. Control Statements, Part 1; Intro to C++20 Text Formatting 4. Control Statements, Part 2 5. Functions Part 2: Arrays, Pointers, Strings and Files 6. array, vectors, C++20 Ranges and Functional-Style Programming 7. (Downplaying) Pointers in Modern C++ 8. string, Regular Expressions and Files Part 3: Object-Oriented Programming 9. Classes 10. Inheritance and Polymorphism 11. Operator Overloading 12. Exceptions: A Deeper Look Part 4: Standard Library Containers, Iterators and Algorithms 13. Standard Library Containers and Iterators 14. Standard Library Algorithms; Functional Programming: A Deeper Look Part 5: Advanced Topics 15. C++20 Modules
  • 24. 16. Intro to Custom Templates and C++20 Concepts 17. Concurrent Programming; Intro to C++20 Coroutines Part 6: Other Topics 18. Stream I/O; C++20 Text Formatting: A Deeper Look 19. Other Topics; A Look Toward C++23 and Contracts Part 7: Appendices A. Operator Precedence and Grouping B. Character Set C. Fundamental Types D. Number Systems E. Preprocessor F. Bits, Characters, C Strings and structs G. C Legacy Code Topics H. Using the Visual Studio Debugger I. Using the GNU C++ Debugger J. Using the Xcode Debugger Contacting the Authors As you read the book, if you have questions, we’re easy to reach at deitel@deitel.com or https://deitel.com/contact-us We’ll respond promptly. For book updates, visit https://deitel.com/c-plus-plus-20-for-programmers Join the Deitel & Associates, Inc. Social Media Communities Join the Deitel social media communities on • Facebook®—https://facebook.com/DeitelFan
  • 25. • LinkedIn®—https://bit.ly/DeitelLinkedIn • Twitter®—https://twitter.com/deitel • YouTube®—https://youtube.com/DeitelTV About the Authors Paul J. Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is an MIT graduate with 39 years of experience in computing. Paul is one of the world’s most experienced programming-languages trainers, having taught professional courses to software developers since 1992. He has delivered hundreds of programming courses to academic, industry, government and military clients internationally, including Pearson Education through O’Reilly Online Learning, Cisco, IBM, Siemens, Sun Microsystems (now Oracle), Dell, Fidelity, NASA at the Kennedy Space Center, the National Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software, Boeing, Nortel Networks, Puma, iRobot, UCLA and many more. He and his co-author, Dr. Harvey M. Deitel, are the world’s best-selling programming-language textbook/professional book/video/webinar authors. Dr. Harvey M. Deitel, Chairman and Chief Strategy Officer of Deitel & Associates, Inc., has 59 years of experience in computing. Dr. Deitel earned B.S. and M.S. degrees in Electrical Engineering from MIT and a Ph.D. in Mathematics from Boston University— he studied computing in each of these programs before they spun off Computer Science. He has extensive college teaching experience, including earning tenure and serving as the Chairman of the Computer Science Department at Boston College before founding Deitel & Associates, Inc., in 1991 with his son, Paul. The Deitels’ publications have earned international recognition, with more than 100 translations published in Japanese, German, Russian, Spanish, French, Polish, Italian, Simplified Chinese, Traditional Chinese, Korean, Portuguese, Greek, Urdu and Turkish. Dr. Deitel has delivered hundreds of programming courses to academic, corporate, government and military clients. About Deitel® & Associates, Inc. Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationally recognized authoring and corporate training organization, specializing in computer programming languages, object technology, mobile
  • 26. app development and Internet-and-web software technology. The company’s training clients include some of the world’s largest companies, government agencies, branches of the military, and academic institutions. The company offers instructor-led training courses delivered at client sites worldwide on major programming languages. Through its 45-year publishing partnership with Pearson/Prentice Hall, Deitel & Associates, Inc., publishes leading-edge programming textbooks and professional books in print and e-book formats, LiveLessons video courses, O’Reilly Online Learning live webinars and Revel™ interactive multimedia courses. To learn more about Deitel on-site corporate training, visit https://deitel.com/training To request a proposal for on-site, instructor-led training worldwide, write to: deitel@deitel.com Individuals wishing to purchase Deitel books can do so at https://www.amazon.com Bulk orders by corporations, the government, the military and academic institutions should be placed directly with Pearson. For more information, visit https://www.informit.com/store/sales.aspx
  • 27. Part 1: C++ Fundamentals Quickstart
  • 28. Chapter 1. Introduction and Test-Driving a C++ Application
  • 30. Objectives In this chapter, you’ll do one or more of the following: ■ Test-drive a C++20 application in the Visual C++ compiler in Microsoft Visual Studio Community edition on Windows. ■ Test-drive a C++20 application in the Clang compiler in Xcode on macOS. ■ Test-drive a C++20 application in the GNU C++ compiler on Linux. ■ Test-drive a C++20 application in the GNU Compiler Collection (GCC) Docker Container in Docker running natively over Windows 10, macOS and/or Linux. 1.1 Introduction 1.2 Test-Driving a C++20 Application 1.2.1 Compiling and Running a C++20 Application with Visual Studio 2019 Community Edition on Windows 10 1.2.2 Compiling and Running a C++20 Application with Xcode on macOS 1.2.3 Compiling and Running a C++20 Application with GNU C++ on Linux 1.2.4 Compiling and Running a C++20 Application with GNU C++ in the GCC Docker Container in Docker Running Natively Over Windows 10, macOS and/or Linux 1.1 Introduction Welcome to C++—one of the world’s most widely used, high-performance, computer-programming languages—and its current version C++20. If you’re reading this, you’re on the O’Reilly Online Learning platform (formerly called Safari) viewing an early-access Rough Cut of our forthcoming book C++20 for Programmers, scheduled for publication this summer. We have prepared this content carefully, but it has not yet been peer reviewed or copy edited and is subject to change. When we complete this chapter, we’ll post the reviewed and copy edited version here.
  • 31. Please send any corrections, comments, questions and suggestions for improvement to paul@deitel.com and I’ll respond promptly. Check for updates here and on the book’s web page: https://deitel.com/c-plus-plus-20-for-programmers This book is written for developers using one or more of the following popular desktop platforms—Microsoft Windows 10, macOS and Linux. We tested every program on three popular free compilers: • Visual C++ in Microsoft Visual Studio Community edition on Windows 10, • Clang in Xcode on macOS, and • GNU C++ on Linux and in the GNU Compiler Collection (GCC) Docker container.1 1. At Deitel, we use current, powerful multicore Apple Mac computers that enable us to run macOS natively, and Windows 10 and Linux through virtual machines in VMWare Fusion. Docker runs natively on Windows, macOS and Linux systems. This early-access version of Chapter 1 contains test-drives demonstrating how to compile and run a C++20 application using these compilers and platforms. The published version of this chapter will contain additional introductory material. At the time of this writing, some C++20 features are fully implemented in all three compilers, some are implemented in a subset of the three and some are not implemented at all. We point out these issues as appropriate and will update our online content as the compiler vendors implement the rest of C++20’s features. C++20 compiler support for many more compilers is tracked at: https://en.cppreference.com/w/cpp/compiler_support “Sneak Peek” Videos for O’Reilly Online Learning Subscribers As an O’Reilly Online Learning subscriber, you also have access to the “sneak peek” of our new C++20 Fundamentals LiveLessons videos at: https://learning.oreilly.com/videos/c-20-fundamentals-part
  • 32. Co-author Paul Deitel immediately records each video lesson as we complete the corresponding chapter. Lessons go live on O’Reilly Online Learning a few days later. Again, check here frequently for updates. 1.2 Test-Driving a C++20 Application In this section, you’ll compile, run and interact with your first C++ application—a guess-the-number game, which picks a random number from 1 to 1000 and prompts you to guess it. If you guess correctly, the game ends. If you guess incorrectly, the application indicates whether your guess is higher or lower than the correct number. There’s no limit on the number of guesses you can make. Usually, this application randomly selects the correct answer as you execute the program. We’ve disabled that aspect of the application so that it uses the same correct answer every time the program executes (though this may vary by compiler). So, you can use the same guesses we use and see the same results. Summary of the Test-Drives We’ll demonstrate running a C++ application using: • Microsoft Visual Studio 2019 Community edition for Windows (Section 1.2.1) • Clang in Xcode on macOS (Section 1.2.2). • GNU C++ in a shell on Linux (Section 1.2.3) • GNU C++ in a shell running inside the GNU Compiler Collection (GCC) Docker container. This requires Docker to be installed and running. You need to read only the section that corresponds to your platform. At the time of this writing, GNU C++ supports the most C++20 features of the three compilers we use. 1.2.1 Compiling and Running a C++20 Application with Visual Studio 2019 Community Edition on Windows 10 In this section, you’ll run a C++ program on Windows using Microsoft Visual Studio 2019 Community edition. There are several versions of Visual Studio available—on some versions, the options, menus and instructions we
  • 33. present might differ slightly. From this point forward, we'll simply say “Visual Studio” or “the IDE.” Step 1: Checking Your Setup If you have not already done so, read the Before You Begin section of this book for instructions on installing the IDE and downloading the book’s code examples. Step 2: Launching Visual Studio Open Visual Studio from the Start menu. The IDE displays the following Visual Studio 2019 window containing: Close this window for now by clicking the X in its tab—you can access this window any time by selecting File > Start Window. We use the > character to indicate selecting a menu item from a menu. For example, the notation File > Open indicates that you should select the Open menu item from the File menu.
  • 34. Step 3: Creating a Project A project is a group of related files, such as the C++ source-code files that compose an application. Visual Studio organizes applications into projects and solutions, which contain one or more projects. Multiple-project solutions are used to create large-scale applications. Each application in this book requires only a single-project solution. To work our code examples, you’ll begin with an Empty Project and add files to it. To create a project: 1. Select File > New > Project… to display the Create a New Project dialog: 2. In the preceding dialog, select the Empty Project template with the tags C++, Windows and Console. This template is for programs that execute at the command line in a Command Prompt window.
  • 35. Depending on the version of Visual Studio you’re using and the options you have installed, there may be many other project templates installed. You can narrow down your choices using the Search for templates textbox and the drop-down lists below it. Click Next to display the Configure your new project dialog: 3. Provide a Project name and Location for your project. For the Project name, we specified cpp20_test. For the Location, we selected the examples folder containing this book’s code examples. Click Create to open your new project in Visual Studio. At this point, the Visual Studio creates your project, places its folder in C:UsersYourUserAccountDocumentsexamples (or the folder you specified) and opens the main window:
  • 36. This window displays editors as tabbed windows (one for each file) when you’re editing code. On the left side is the Solution Explorer for viewing and managing your application’s files. In this book’s examples, you’ll typically place each program’s code files in the Source Files folder. If the Solution Explorer is not displayed, you can display it by selecting View > Solution Explorer. Step 4: Adding the GuessNumber.cpp File into the Project Next, you’ll add GuessNumber.cpp to the project you created in Step 3. In the Solution Explorer: 1. Right-click the Source Files folder and select Add > Existing Item…. 2. In the dialog that appears, navigate to the ch01 subfolder of the book’s examples folder, GuessNumber.cpp and click Add.2 2. For the multiple source-code-file programs that you’ll see in later chapters, select all the files for a given program. When you begin creating programs yourself, you can right click the Source Files folder and select Add > New Item… to display a dialog for adding a new file. Step 5: Configuring Your Project to Use C++20 The Visual C++ compiler in Visual Studio supports several versions of the C++ standard. For this book, we use C++20, which we must configure in our project’s settings:
  • 37. 1. Right-click the project’s node— —in the Solution Explorer and select Properties to display the project’s cpp20_test Property Pages dialog: 2. In the left column, expand the C/C++ node, then select Language. 3. In the right column, click in the field to the right of C++ Language Standard, click the down arrow, then select Preview - Features from the Latest C++ Working Draft (/std:c++latest) and click OK. In a future version of Visual Studio, Microsoft will change this option to ISO C++20 Standard (/std:c++20). Step 6: Compiling and Running the Project To compile and run the project so you can test-drive the application, select Debug > Start without debugging or type Ctrl + F5. If the program
  • 38. compiles correctly, Visual Studio opens a Command Prompt window and executes the program. We changed the Command Prompt’s color scheme and font size for readability: Step 7: Entering Your First Guess At the ? prompt, type 500 and press Enter. The application displays "Too high. Try again." to indicate the value you entered is greater than the number the application chose as the correct guess: Step 8: Entering Another Guess At the next prompt, type 250 and press Enter. The application displays "Too high. Try again.", because the value you entered once again is greater than the correct guess:
  • 39. Step 9: Entering Additional Guesses Continue to play the game by entering values until you guess the correct number. When you guess correctly, the application displays "Excellent! You guessed the number!": Step 10: Playing the Game Again or Exiting the Application After you guess the correct number, the application asks if you’d like to play another game. At the "Would you like to play again (y or n)?" prompt, entering y causes the application to choose a new number and start a new game. Entering n terminates the application. Each time you
  • 40. execute this application from the beginning (Step 6), it will choose the same numbers for you to guess. Reusing This Project for Subsequent Examples You can follow the steps in this section to create a separate project for every application in the book. However, for our examples, you may find it more convenient to remove the current program from the project then add a new one. To remove a file from your project (but not your system), select it in the Solution Explorer then press Del (or Delete). You can then repeat Step 4 to add a different program to the project. 1.2.2 Compiling and Running a C++20 Application with Xcode on macOS In this section, you’ll run a C++ program on a macOS using the Clang compiler in Apple’s Xcode IDE. Step 1: Checking Your Setup If you have not already done so, read the Before You Begin section of this book for instructions on installing the IDE and downloading the book’s code examples. Step 2: Launching Xcode Open a Finder window, select Applications and double-click the Xcode icon ( ). If this is your first time running Xcode, the Welcome to Xcode window appears:
  • 41. Close this window by clicking the X in the upper left corner—you can access it any time by selecting Window > Welcome to Xcode. We use the > character to indicate selecting a menu item from a menu. For example, the notation File > Open… indicates that you should select the Open… menu item from the File menu. Step 3: Creating a Project A project is a group of related files, such as the C++ source-code files that compose an application. The Xcode projects we created for this book’s examples are Command Line Tool projects that you’ll execute directly in the IDE. To create a project: 1. Select File > New > Project…. 2. At the top of the Choose a template for your new project dialog, click macOS. 3. Under Application, click Command Line Tool and click Next. 4. For Product Name, enter a name for your project—we specified cpp20_test. 5. In the Language drop-down list, select C++ then click Next.
  • 42. 6. Specify where you want to save your project. We selected the examples folder containing this book’s code examples. 7. Click Create. Xcode creates your project and displays the workspace window initially showing three areas—the Navigator area, Editor area and Utilities area: The left-side Navigator area has icons at its top for the navigators that can be displayed there. For this book, you’ll primarily work with • Project ( )—Shows all the files and folders in your project. • Issue ( )—Shows you warnings and errors generated by the compiler. Clicking a navigator button displays the corresponding navigator panel. The middle Editor area is for managing project settings and editing source code. This area is always displayed in your workspace window. Selecting a file in the Project navigator, the file’s contents display in the Editor area. You will not use the right-side Utilities area in this book. There’s also a Debug area in which you’ll run and interact with the guess-the-number program. This will appear below the Editor area. The workspace window’s toolbar contains options for executing a program:
  • 43. displaying the progress of tasks executing in Xcode: and hiding or showing the left (Navigator), right (Utilities) and bottom (Debug) areas: Step 4: Configuring the Project to Compile Using C++20 The Clang compiler in Xcode supports several versions of the C++ standard. For this book, we use C++20, which we must configure in our project’s settings: 1. In the Project navigator, select your project’s name (cpp20_test). 2. In the Editors area’s left side, select your project’s name under TARGET. 3. At the top of the Editors area, click Build Settings, and just below it, click All. 4. Scroll to the Apple Clang - Language - C++ section. 5. Click the value to the right of C++ Language Dialect and select Other…. 6. In the popup area, replace the current setting with c++2a and press Enter. In a future version of Xcode, Apple will provide a C++20 option for C++ Language Dialect. Step 5: Deleting the main.cpp File from the Project By default, Xcode creates a main.cpp source-code file containing a simple program that displays "Hello, World!". You won’t use main.cpp in this test-drive, so you should delete the file. In the Project navigator, right- click the main.cpp file and select Delete. In the dialog that appears, select Move to Trash. The file will not be removed from your system until you empty your trash.
  • 44. Step 6: Adding the GuessNumber.cpp File into the Project In a Finder window, open the ch01 folder in the book’s examples folder, then drag GuessNumber.cpp onto the Guess Number folder in the Project navigator. In the dialog that appears, ensure that Copy items if needed is checked, then click Finish.3 3. For the multiple source-code-file programs that you’ll see later in the book, drag all the files for a given program to the project’s folder. When you begin creating your own programs, you can right click the project’s folder and select New File… to display a dialog for adding a new file. Step 7: Compiling and Running the Project To compile and run the project so you can test-drive the application, simply click the run ( ) button on Xcode’s toolbar. If the program compiles correctly, Xcode opens the Debug area and executes the program in the right half of the Debug area: The application displays "Please type your first guess.", then displays a question mark (?) as a prompt on the next line. Step 8: Entering Your First Guess Click in the Debug area, then type 500 and press Return The application displays "Too low. Try again.", meaning that the value you entered is less than the number the application chose as the correct guess. Step 9: Entering Another Guess
  • 45. At the next prompt, enter 750: The application displays "Too low. Try again.", because the value you entered once again is less than the correct guess. Step 10: Entering Additional Guesses Continue to play the game by entering values until you guess the correct number. When you guess correctly, the application displays "Excellent! You guessed the number.": Playing the Game Again or Exiting the Application After you guess the correct number, the application asks if you’d like to play another game. At the "Would you like to play again (y or n)?" prompt, entering y causes the application to choose a new number and start a new game. Entering n terminates the application. Each time you execute this application from the beginning (Step 7), it will choose the same numbers for you to guess.
  • 46. Reusing This Project for Subsequent Examples You can follow the steps in this section to create a separate project for every application in the book. However, for our examples, you may find it more convenient to remove the current program from the project then add a new one. To remove a file from your project (but not your system), right-click the file in the Project navigator and select Delete. In the dialog that appears, select Move to Trash. You can then repeat Step 6 to add a different program to the project. 1.2.3 Compiling and Running a C++20 Application with GNU C++ on Linux For this test drive, we assume that you read the Before You Begin section and that you placed the downloaded examples in your user account’s Documents folder. Step 1: Changing to the ch01 Folder From a Linux shell, use the cd command to change to the ch01 subfolder of the book’s examples folder: Click here to view code image ~$ cd ~/Documents/examples/ch01 ~/Documents/examples/ch01$ In this section’s figures, we use bold to highlight the text that you type. The prompt in our Ubuntu Linux shell uses a tilde (~) to represent the home directory. Each prompt ends with the dollar sign ($). The prompt may differ on your Linux system. Step 2: Compiling the Application Before running the application, you must first compile it: Click here to view code image ~/Documents/examples/ch01$ g++ -std=c++2a GuessNumber.cpp - ~/Documents/examples/ch01$
  • 47. The g++ command compiles the application: • The -std=c++2a option indicates that we’re using C++20—c++2a will become c++20 in a future GNU C++ release. • The -o option names the executable file (GuessNumber) that you’ll use to run the program. Step 3: Running the Application Type ./GuessNumber at the prompt and press Enter to run the program: Click here to view code image ~/Documents/examples/ch01$ ./GuessNumber I have a number between 1 and 1000. Can you guess my number? Please type your first guess. ? The ./ tells Linux to run a file from the current directory and is required to indicate that GuessNumber is an executable file. Step 4: Entering Your First Guess The application displays "Please type your first guess.", then displays a question mark (?) as a prompt on the next line. At the prompt, enter 500—note that the outputs may vary based on the compiler you’re using: Click here to view code image ~/Documents/examples/ch01$ ./GuessNumber I have a number between 1 and 1000. Can you guess my number? Please type your first guess. ? 500 Too high. Try again. ?
  • 48. The application displays "Too high. Try again.", meaning that the value you entered is greater than the number the application chose as the correct guess. Step 5: Entering Another Guess At the next prompt, enter 250: Click here to view code image ~/Documents/examples/ch01$ ./GuessNumber I have a number between 1 and 1000. Can you guess my number? Please type your first guess. ? 500 Too high. Try again. ? 250 Too low. Try again. ? This time the application displays "Too low. Try again.", because the value you entered is less than the correct guess. Step 6: Entering Additional Guesses Continue to play the game by entering values until you guess the correct number. When you guess correctly, the application displays "Excellent! You guessed the number.": Click here to view code image Too low. Try again. ? 375 Too low. Try again. ? 437 Too high. Try again. ? 406 Too high. Try again. ? 391
  • 49. Too high. Try again. ? 383 Too low. Try again. ? 387 Too high. Try again. ? 385 Too high. Try again. ? 384 Excellent! You guessed the number. Would you like to play again (y or n)? Step 7: Playing the Game Again or Exiting the Application After you guess the correct number, the application asks if you’d like to play another game. At the "Would you like to play again (y or n)?" prompt, entering y causes the application to choose a new number and start a new game. Entering n terminates the application and returns you to the shell. Each time you execute this application from the beginning (Step 3), it will choose the same numbers for you to guess. 1.2.4 Compiling and Running a C++20 Application with GNU C++ in the GCC Docker Container in Docker Running Natively Over Windows 10, macOS and/or Linux At the time of this writing, GNU C++ implements the most C++20 features. For this reason, you may want to use the latest GNU C++ compiler on your system. One of the most convenient cross-platform ways to do this is by using the GNU Compiler Collection (GCC) Docker container. This section assumes you’ve already installed Docker Desktop (Windows or macOS) or Docker Engine (Linux). Executing the GNU Compiler Collection (GCC) Docker Container Open a Command Prompt (Windows), Terminal (macOS/Linux) or shell (Linux), then perform the following steps to launch the GCC Docker Container: 1. Use the cd command to navigate to the examples folder containing this book’s examples.
  • 50. 2. Windows users: Launch the GCC docker container with the command Click here to view code image docker run --rm -it -v "%CD%":/usr/src gcc:latest 3. macOS/Linux users: Launch the GCC docker container with the command Click here to view code image docker run --rm -it -v "$(pwd)":/usr/src gcc:latest In the preceding commands: • --rm cleans up the container’s resources when you eventually shut it down. • -it runs the container in interactive mode, so you can enter commands to change folders and to compile and run programs using the GNU C++ compiler. • -v "%CD%":/usr/src (Windows) or -v "$(pwd)":/usr/src (macOS/Linux) allows the Docker container to access your local system files in the folder from which you executed the docker run command. In the Docker container, you’ll navigate with the cd command to subfolders of /usr/src to compile and run the C++ code. • gcc:latest is the container name. The :latest specifies that you want to use the most up-to-date version of the gcc container. Each time you execute the preceding docker run commands, Docker checks whether you have the latest gcc container version. If not, Docker downloads it before executing the container. Once the container is running, you’ll see a prompt like: root@67773f59d9ea:/# The container uses a Linux operating system. It’s prompt displays the current folder location between the : and #. Changing to the ch01 Folder in the Docker Container The docker run command specified above attaches your examples
  • 51. folder to the containers /usr/src folder. In the docker container, use the cd command to change to the ch01 sub-folder of /usr/src: Click here to view code image root@01b4d47cadc6:/# cd /usr/src/ch01 root@01b4d47cadc6:/usr/src/ch01# To compile, run and interact with the GuessNumber application in the Docker container, follow Steps 2–7 of Section 1.2.3’s GNU C++ Test-Drive. Terminating the Docker Container You can terminate the Docker container by typing Ctrl + d at the container’s prompt.
  • 52. Chapter 2. Introduction to C++ Programming
  • 54. Objectives In this chapter, you’ll: ■ Write simple C++ applications. ■ Use input and output statements. ■ Use fundamental data types. ■ Use arithmetic operators. ■ Understand the precedence of arithmetic operators. ■ Write decision-making statements. ■ Use relational and equality operators. ■ Begin appreciating the “objects natural” learning approach by creating and using objects of the C++ standard library’s string class before creating your own custom classes. Outline 2.1 Introduction 2.2 First Program in C++: Displaying a Line of Text 2.3 Modifying Our First C++ Program 2.4 Another C++ Program: Adding Integers 2.5 Arithmetic 2.6 Decision Making: Equality and Relational Operators 2.7 Objects Natural: Creating and Using Objects of Standard Library Class string 2.8 Wrap-Up 2.1 Introduction This chapter presents several code examples that demonstrate how your programs can display messages and obtain data from the user for processing. The first three display messages on the screen. The next obtains two numbers from a user at the keyboard, calculates their sum and displays the result—the
  • 55. Another Random Scribd Document with Unrelated Content
  • 56. Aug. 14. Aug. 15. Divisions) under Sir Douglas Haig, at Wassigny; the Headquarters of the Second Corps (the Third and Fifth Divisions), under Sir Horace Smith-Dorrien, at Nouvion; while the Cavalry Division, under General Allenby, was sent to Maubeuge. It was a scorching, airless day, and the march to camp was a very trying one. But after a good sleep and a bathe in the sea the men were thoroughly refreshed and fit. Then, after the usual inspections, they were formed up on parade, and the King's message was read out to them: Message from the King to the Troops of the Expeditionary Force You are leaving home to fight for the safety and honour of my empire. Belgium, whose Country we are pledged to defend, has been attacked and France is about to be invaded by the same powerful foe. I have implicit confidence in you, my soldiers. Duty is your watchword, and I know your duty will be nobly done. I shall follow your every movement with deepest interest and mark with eager satisfaction your daily progress, indeed your welfare will never be absent from my thoughts. I pray God to bless you and guard you and bring you back victorious. George R.I. The whole population of Havre seemed to have come out to see the Battalion when it marched the same evening to the entraining point. The crowd cheered and shouted, and the men responded with "The Marseillaise." When they reached the siding the disappointing news met them that the train would not start for another four hours. It began to rain heavily, but fortunately there were large hangars available, into which the men crowded for shelter. Eventually when the train arrived at 2 A.M., the men were packed into it, and very crowded they were. Sleep was difficult, as the horse-wagons attached to the train were loosely coupled, and there was a succession of bumps whenever the train stopped or slowed down.
  • 57. The first real stop was at Rouen, where provisions were obtained for the men, and then the train bumped on to Amiens. Route of the Second Battalion, 1914 Fervent scenes of welcome went on all along the line. Each little wayside station, every bridge and level-crossing held a cheering throng. At Arras the Mayor turned out in state with a number of local magnates, and presented three large bouquets, for which Colonel Corry returned thanks on behalf of the officers, in his best French.
  • 58. Aug. 16-20. Aug. 20-22. A touch of humour was not wanting at the little ceremony—if any one had been in the mood to seize hold of it. For, caught unawares, Colonel Corry, Lord Loch, and Lord Bernard Gordon-Lennox were anything but arrayed for a function, in fact, in a state of decided deshabille. But such was the enthusiasm of the inhabitants that a trifle like this passed unnoticed or unconsidered. The stationmaster here said he was passing trains through at the rate of one every ten or fifteen minutes, which gives some idea of the great concentration of troops that was going on. Slowly the train went on through Cambrai, Busigny, and Vaux Andigny to Flavigny, where, in pouring rain, the Battalion detrained and went into billets—surprisingly well arranged; but then Flavigny had plenty of experience in that way, and only a few days before had lodged the French troops. Next morning parade was at 7 o'clock for the march to Grougis, about seven and a half miles off, where four days were spent in billets, and Colonel Corry took advantage of the breathing space to have his officers and men inoculated against typhoid. The concentration of the British Force in the Busigny area was now completed, and the advance towards Mons was to begin the next day. Off again on the 20th, the Battalion marched to Oisy (where it was again billeted), and on the following days to Maroilles and La Longueville. Here for the first time it heard the guns, and realised that very soon it would be getting to work. On the 21st, following the plan concerted with General Joffre, Sir John French took up a defensive position from Condé on the west to Binche to the east—a front of about twenty-five miles. The British Army was thus on the extreme left of the French lines. To the First Corps was assigned the easterly position from Mons to Binche, while
  • 59. Aug. 23. the Second Corps lined the canal from Mons to Condé, the whole front being covered by the 5th Cavalry Brigade. Originally the scheme appears to have been to await the enemy's onslaught on the Charleroi—Mons line, and then to assume the offensive and advance into Belgium. How far-reaching the German preparations had been was at that time hardly recognised, and neither the French nor the British Commander-in-Chief seems to have had any conception of the overwhelming force which the Germans had been able to concentrate against them. From La Longueville the 2nd Battalion Grenadiers marched on August 23, during the last stages of its journey, across the field of Malplaquet, where more than 200 years before the regiment had fought with distinction, through Blaregnies and Genly to the outskirts of Mons, where it bivouacked. There it received orders to advance, which were countermanded before they could be carried out, and the Battalion was told to remain where it was. There was nothing to do but have breakfast and an hour's sleep by the roadside, with showers falling at intervals. All the time heavy firing could be heard from the direction of Mons, and shells bursting could be observed in the distance. Orders then came for the Battalion to march back to Quevy le Petit, about five miles off, where the men fondly imagined they would again be comfortably billeted. But hardly had they arrived there when they were sent forward again. As they were marching down a dusty track General Scott-Kerr rode up, and directed the 2nd Battalion Grenadiers and the Irish Guards to move up close behind the ridge east of Spiennes in support of the Irish Rifles. At the same time the two Coldstream battalions were ordered to entrench themselves just east of Harveng, presumably as a precaution in case the Brigade should have to retire. Heavy firing was now going on all round, and the ridge which overlooked St. Symphorien to the north was being vigorously shelled by the Germans, who had got the
  • 60. range to a nicety, and were bursting their shells over it with accuracy. It was about 6 P.M. when the Battalion, advancing through Harveng, proceeded in artillery formation for about one and a half miles to the hill near Spiennes. The men huddled close together under the banks on the reverse slope of the hill just over the railway line, while bullets and shells whistled over their heads. As they were lying there they were amused to see the signalman walk slowly down the line as if nothing in particular was happening. He had to light the lamps, and saw no reason why the ordinary routine which he had carried out probably for many years should be interfered with. One of the officers called out to him in French, and explained that the Germans were advancing, but he merely murmured "ça m'est égal," and continued his work, apparently unconscious of the bullets that were striking the line. Meanwhile, Colonel Corry and Major Jeffreys went up to the position occupied by the Irish Rifles, who were holding their own well under a heavy rifle fire. When they returned to their men it was getting dark, and at 10.30 a message came from the O.C. Irish Rifles, that his battalion was retiring. It appeared therefore to Colonel Corry that the position was becoming untenable, since the Irish Rifles on his left had already retired, and both flanks of the Battalion were exposed. He consulted Colonel Morris of the Irish Guards, and they both came to the conclusion that the best course would be to retire to Harveng. The difficulty was to communicate with the Brigadier. The telephone to Brigade Headquarters had been cut by shell-fire, and so Colonel Corry rode back to find General Scott-Kerr. He could not be discovered, and was reported to have gone to Divisional Headquarters. There seemed no prospect whatever of finding him, and it was now past midnight. Thereupon Colonel Corry determined to take upon himself the responsibility of ordering the retirement of the two battalions. His impression was that in a case like this, when local conditions could not be known to the Divisional Staff, it was for the man on the spot to make his own decision.
  • 61. Aug. 24. Superior authority, however, afterwards held that while under exceptional circumstances such powers might well be delegated to the man in mediis rebus, in a case like this it could not be admitted that an officer in actual touch with the enemy was the best judge of how long a position should be held. It was felt that there were many considerations in a decision of this sort, of which the officer in the front line could know very little. Colonel Corry was therefore severely blamed for his action, and was a fortnight later relieved of his command. At 1 o'clock in the morning the 2nd Battalion Grenadiers and the Irish Guards retired, but they had only gone a couple of miles towards Harveng when they were ordered to go back and occupy the ridge they had just left. Back they went, and got as far as the foot of the hill, only to receive another order to retire to Harveng. By this time the men were absolutely tired out. They had started at 3.30 the previous morning, and had been on the move for twenty-four hours, with only occasional halts by the roadside. It was just at this point in the engagement that Sir John French received what he described in his despatch as a most unexpected message. It came from General Joffre, who informed him that the French Forces had been compelled, by superior numbers, to retire, and that consequently the Fifth French Army, which was immediately on our right, had vacated its line. Two German corps were advancing on the British position, while a third corps was engaged in a turning movement in the direction of Tournai. Divisions of French Territorials had been promised in support of the left flank, but, except for a Brigade at Tournai, no French troops arrived from the west. There was therefore no alternative for Sir John French but to retire.
  • 62. Aug. 24. CHAPTER III THE RETREAT FROM MONS (2ND BATTALION) Thus began that historic, terrible, splendid retreat from Mons. Long weary marches were to be the lot of the British Army for many a day, but fortunately no one realised what lay ahead, or the stoutest hearts might well have quailed. Long before it was over, the men's boots—not Crimean ones of brown paper, but good, sound English leather—had been worn into shreds by those interminable, pitiless paving-stones, that had withstood centuries of traffic. Even the men with the toughest skins suffered badly from their feet. Clouds of dust and the heavy atmosphere arising from men in close formation added to the trials of marching. Constant cries of "Feel your right" (to let cavalry or wagons pass by), the wearisome burden of the pack on the shoulders, which drove many men to throw away their most prized possessions, the frequent futile digging of trenches, abandoned as soon as they were dug, the orders and counter-orders—all made the days that followed a positive nightmare to the Army. Such continuous retirement had never been practised. It was against all tradition, and the men grumbled constantly at the seemingly never-ending retreat. But what other course could the "contemptible little army" have followed in the face of the enemy's overwhelming force? On the 24th Sir H. Smith-Dorrien started off with the Second Corps, while a demonstration was made by the First Corps in the direction of Binche, and dug a line four miles south of Mons to enable the First
  • 63. Corps to retire. It was evident that the Germans were straining every effort to surround the British Army, and therefore to hold on too long to any line was extremely dangerous. The Fifth French Army was still in full retirement, and the First French Cavalry Corps was so exhausted that General Sordet could promise no assistance. The greater part of the British Cavalry Division, with the exception of the regiments covering the retreat of the two British Corps, was guarding the left flank. The arrival of the Fourth Division at Le Cateau had been a welcome addition, but as it was only too probable that the Germans would make every effort to envelop the left of the whole line of the Allies, it was important to have strong reinforcements on that flank.
  • 65. Aug. 25. Landrecies. Route taken by the Second Batt. Grenadier Guards during the Retreat from Mons, and subsequent advance to the Marne and the Aisne. 1914. Two hours' sleep was all the 2nd Battalion Grenadiers was allowed on that fateful 24th of August, weary as it was after its twenty-four hours on end of marching and fighting. At daybreak it marched to Quevy le Grand, where the men were ordered to dig themselves in. They were quite in the dark about what was going on round them. What force was opposed to them or why they were retiring, no one knew. The greatest secrecy prevailed. Although it was cold and foggy early, it soon became scorching hot and the men were tired, but when the word went round that this was not a rearguard action, but a determined stand, the digging became a serious matter, and they set to with a will. The Germans advanced very slowly and cautiously, gradually pushing back our Cavalry Patrols, who could be seen retiring. They shelled the Mons—Maubeuge Road and also Quevy le Grand, but as the line of the road was not held, our position being some hundreds of yards in rear of it, little damage was done, although a few men were hit in the village. But at 2 P.M. another order came to evacuate the trenches and concentrate on the left. "Concentration" proved to be a euphemism for further retirement, and after a long and dusty march the Battalion bivouacked south of La Longueville. Next morning at 5 o'clock it started on another hot and lengthy march through Pont sur Sambre, Leval, and Noyelles to Landrecies, which was reached at 4 P.M. It went into billets and settled down to rest. But soon afterwards a trooper from the cavalry patrols rode into the town with the news that the Germans were coming; the alarm was given, and the men stood to arms. Nothing further happened, however, and they returned to their billets. The 3rd Battalion Coldstream provided the outposts, and the rest of the brigade were just settling down once more in the hope of a restful night when a
  • 66. second alarm sounded. This time it was a real one. The Germans were advancing in force on Maroilles and Landrecies. Though the night was very dark there was no confusion, as the men poured hurriedly out from their billets to fall in. Some were at once detailed to build emergency barricades in the streets, and as the tool limbers were taken for this purpose the Battalion never had any heavy tools for the rest of the retreat. The houses on the front of the town were rapidly put in a state of defence; loopholes were made, and the furniture, or anything handy, was pushed up to make the walls bullet-proof. As it turned out, the enterprise of a small patrol of Uhlans, who rode unopposed into the town during the afternoon, had proved a very fortunate thing for the defenders. For it seems to have been assumed at first that the town was covered by troops from other brigades, and when the 3rd Battalion Coldstream was ordered to furnish outposts it had been considered a quite unnecessary precaution. After the Uhlan incursion, even the most optimistic could hardly have needed convincing. When all the dispositions had been made the 2nd Battalion Grenadiers was distributed as follows: Nos. 2 and 3 Companies, under the command of Major Lord Bernard Lennox and Captain Stephen, held the level-crossing over the railway, and watched the right and left flanks of the road leading over the Sambre. No. 1 Company, under Major Hamilton, held the two sides on the left, while No. 4 Company, under Captain Colston, in reserve, was posted on the bridge over the Sambre. The first warning that the enemy was at hand was given at 8 P.M. by the firing of the picquets. When the alarm went there was still sufficient light for the men to get into their positions, but soon after it became pitch dark, and the rain began to fall. Suddenly shadowy forms were observed by the outposts moving in the darkness. Evidently they realised that they had been seen, for a voice was heard calling out, "Don't shoot. We are the French." The trick at that
  • 67. time was new to us. Our men naturally hesitated at first to fire, and this gave the Germans their opportunity for a forward rush. Very critical moments followed. The two forces were only a short distance apart, and in the darkness a retreat would have been fatal, but the splendid discipline of the Guards saved the situation. Everywhere the attacking Germans found themselves beating up against a wall of stubborn resistance. They brought up a couple of guns and poured shells into the town at almost point-blank range; they even fired case-shot down the road. Again and again they charged, only to be met and mowed down by a withering fire. The machine-guns of the Grenadiers were moved up to help the Coldstream, and came into action at a very critical moment. They were largely instrumental in repelling the enemy's attack, and were well handled by Lieutenant the Hon. W. Cecil, who was slightly wounded. Private Rule particularly distinguished himself by sticking to his gun and continuing to fight it, although he had been blown off his feet by the blast of a H.E. shell. The brunt of the attack was borne at the start by the 3rd Battalion Coldstream, which lost heavily in this fight; but in the Grenadiers the casualties were not great. Soon burning houses were lighting up the battlefield, and it began to be possible to distinguish friend from foe. During one of the bursts of firing Lieutenant Vereker was hit, and fell shot through the head. After the first heavy attacks had been repulsed, the enemy tried to get round the left of the Coldstream in the direction of the railway- station, but there was met by a steady fire from No. 2 Company, under Major Lord Bernard Lennox, and could make no headway. Splendid work was done by a field howitzer, which had been manhandled up to the level-crossing, and which succeeded in silencing the enemy's guns.
  • 68. Sketch plan of Landrecies. Finally, about midnight, the enemy evidently realised the futility of going on with the attack, and retreated once more into the
  • 69. Aug. 26. darkness. But spasmodic firing continued for some time, and it was not until nearly 2 A.M. that the night became still, and the men were able to strengthen their position. It was afterwards learnt that the Germans who took part in the attack had been pushed up to Landrecies in two hundred motor lorries. How severely they had been handled may be surmised from the fact that they allowed the Grenadiers and 3rd Battalion Coldstream to retire unmolested over a single bridge across the Sambre. Writing of this engagement in his despatch of September 7, Sir John French said: The 4th Guards Brigade in Landrecies was heavily attacked by troops of the Ninth German Army Corps, who were coming through the forest on the north of the town. This brigade fought most gallantly and caused the enemy to suffer tremendous loss in issuing from the forest into the narrow streets of the town. This loss has been estimated from reliable sources at from 700 to 1000. In the meantime the Second Corps was between Le Cateau and Caudry with the 19th Brigade, which had been brought up from the lines of communication on the left and the Fourth Division south of Cambrai. The German First Army launched a serious attack along the whole of this line, and Sir H. Smith-Dorrien, finding himself outnumbered and out-gunned, had the greatest difficulty in breaking off the engagement and continuing the retirement. At daybreak the 4th Brigade again got orders to retire, and marched unmolested to Etreux. Unfortunately many of the men had no time to retrieve their kits, which they had left at their billets, and all these were left behind. The troops were dead beat, having again had practically no sleep after a long day's marching and fighting. Every time a halt was made the whole Battalion fell fast asleep, and when the march had to be resumed it was very hard to rouse the men. It might seem hardly worth while to sleep during a brief halt of only a few minutes, with the prospect of a painful reawakening to the realities of the situation as the inevitable sequel. But most of the men were so thoroughly worn out that they eagerly welcomed even the doubtful blessing of such a respite. In the distance heavy firing could be
  • 70. Aug. 27. Aug. 28. Aug. 29. heard in the direction of Le Cateau, and at one time it seemed probable the 4th Brigade might be sent off to support the hard- pressed Second Corps. Etreux was reached at last, and the Battalion proceeded to dig itself in. During the afternoon a German aeroplane flew very low over the bivouac, and dropped a bomb, which, however, did no damage. Every one who had a rifle handy had a shot at the unwelcome visitor; eventually it was forced down a mile away, where it was picked up by the cavalry. In it were found three officers, two dead and one wounded. Another long dusty march lay before the Brigade on the following day. Continuing the retirement, it passed through Vénérolles, Tupigny, Vadencourt, and Hauteville to Mont d'Origny. A report was brought in that a large force of the enemy had been seen near St. Quentin, but this proved to be inaccurate. That night the First Corps was in a most critical position. The Germans had nearly surrounded them, and urgent orders to entrench the high ground north and east of Mont d'Origny were received; but although the weary troops dug on till midnight, nothing occurred, and at 3.30 A.M. the Battalion started off again. It reached Deuillet near La Fère, where it had the only day's halt during the retreat. On the way the Scots Greys and 12th Lancers charged a large force of German cavalry and utterly routed them, making many prisoners, but otherwise nothing was seen of the enemy. On arrival at Deuillet, the usual procedure was gone through, and a position in defence was entrenched, the men working at it all day. In the evening an electrifying report, which cheered every one up, went round that there was to be a general advance. But when the order came it was the usual one to retire, and another hot march of twenty-eight miles followed. The weary, wearing ordeal of long day marches and but little sleep had commenced again. As soon as it was decided to
  • 71. Aug. 30-31. Sept. 1. Villers- Cotterêts. continue the retreat, and the whole British Force had crossed over the Oise, the bridges were blown up. The heat was intense. There was practically no wind, and the dust was stifling; a very large number of men were suffering from sore feet, and there was a good deal of grumbling in the ranks at the endless marching in the wrong direction. But there was no prospect of a long rest, and those battalions which were unlucky enough to leave men behind never saw them again. Not a man from the 2nd Grenadiers, however, fell out. The two corps which had been dangerously separated were now once more united, but the pursuing Germans were very near, and the situation still gave rise to much anxiety. Information was received to the effect that five or six German corps were pursuing the Fifth French Army, while at least two corps were advancing on the British Army. The situation on the left of the British Army was obscure, but it was reported that the enemy had three or four more corps endeavouring to creep round that flank. In response to Sir John French's representations, General Joffre ordered the Fifth French Army to attack the enemy on the Somme with the object of relieving the pressure on the British Army. The Battalion reached Soissons about midday on the 30th, and was ordered to occupy the ridge near Pasly, about two miles north of the town. Next day it tramped on to Soucy, a very hard march in great heat, finishing up with a steep climb. Here it bivouacked as usual, and snatched what rest it could. But a full night's sleep was always out of the question, and soon after midnight the whole Brigade was directed to form a rearguard, to cover the retirement of the Second Division. Accordingly trenches were dug in the high ground above Soucy, No. 4 Company Grenadiers being detached to guard the right flank in a position leading across a deep ravine to the high ground above Montgobert. It was to rejoin the Battalion when it retired to the forest of Villers-
  • 72. Cotterêts. Soon after the Germans came in sight, and retirement from the first position was successfully effected. The 2nd Battalion Grenadiers and 3rd Battalion Coldstream made their way into the wood, the edges of which were held by the Irish Guards and 2nd Battalion Coldstream, and took up a fresh position along the line of the main road running east and west through Rond de la Reine. Thick mist hung over the country, and the dense undergrowth made the passage of the wood difficult. The Germans, it was assumed, would not attempt to penetrate the wood, but would be content to use the roads and drives. The assumption proved to be wrong— fortunately for us. As it happened, they came through the very thickest part, and in so doing lost cohesion and direction. Probably, in fact, it was their doing this, and the confusion into which they were consequently thrown, that enabled the 4th Brigade to break off the action later in the evening and retire unmolested. The 2nd Battalion Grenadiers held the right of the line. From a strategic point of view, the position it occupied could not well have been worse. But in a rearguard action there is often no choice. It was absolutely necessary to retard the advance of the enemy through the wood, so that the rest of the Division should get away. During the time of waiting for the oncoming Germans, the Scots Greys and 12th Lancers suddenly appeared, coming down the ride on the right. They had been attracted by the firing, and came to see what was going on. They dismounted, and, finding many friends among the Grenadiers, started "coffee-housing" for a while. But the firing in the outskirts of the wood began to sound serious, and they rode off along the road to the left, with the idea of operating against the enemy's right. A few minutes later the Germans appeared, and a fight at close quarters began. The firing became very hot, as in some places the opposing forces were hardly seventy yards apart. Good work was done by the machine-guns of the Grenadiers and Irish Guards, which accounted for a large number of Germans, while the men charged
  • 73. repeatedly with the bayonet and drove the enemy back. Gallantly, stolidly, the 4th Brigade held on until the order came to retire. Even with highly-disciplined troops, a rear-guard action in a wood is one of the most difficult manoeuvres to carry out well. It is quite impossible for the commanding officer to keep a firm grip of his battalion when it is scattered about in different rides; orders passed along often do not reach all the platoons, and men of different companies, and even regiments, are wont to get hopelessly mixed. Fortunately in the Brigade of Guards the men are all trained on the same system, and, except for some small characteristic differences, a man belonging to one regiment will be quite at home in any of the others. At Villers-Cotterêts the men of the 4th Brigade became very much mixed, and officers took command of the men who happened to be near them. The wood, too, was so thick that at fifty yards' distance parties were practically out of sight of each other. One result of this difficulty of keeping in touch was that two platoons of No. 4 Company never got the order to retire.
  • 74. Engagement at Villers-Cotterêts. September 1. 1914. These two platoons, under the command of Lieutenant the Hon. F. E. Needham and Lieutenant the Hon. J. N. Manners, were at the Cross Roads at Rond de la Reine. As the Germans came on,
  • 75. Brigadier-General Scott-Kerr, finding that they were creeping round his left flank, ordered these two platoons down a ride to the left, to enfilade them. Making the best dispositions they could, these two officers continued to fight, when they suddenly realised that they were cut off and the Germans were on all sides of them. True to the traditions of the Regiment, they stuck to their posts, and fought on till all were killed or wounded. Lieutenant the Hon. J. N. Manners was killed while directing the fire of his platoon, and Lieutenant the Hon. F. Needham, badly wounded, was taken prisoner. Lieutenant G. E. Cecil, another officer belonging to these platoons, seeing the Germans streaming across a ride to his left, dashed off with some men to stop them. He had not gone far before he was shot through the hand; stumbling forward, he recovered his feet, and, drawing his sword, he called on the men to charge when a bullet struck him in the head. And there were other casualties among the officers. Earlier in the day the Adjutant of the Battalion, Lieutenant I. MacDougall, was shot dead while carrying orders to the firing-line. His place was taken by Captain E. J. L. Pike. The Brigadier-General, Scott-Kerr, who rode up to give some orders, was badly wounded in the thigh, and the command of the Brigade passed to Colonel Corry, while Major Jeffreys took over the 2nd Battalion Grenadiers. Field-Marshal Sir John French, on hearing of this, sent the following telegram to Brigadier-General Scott-Kerr, care of Communications: My warm congratulations on gallantry of your Brigade A A A am deeply grieved to hear you are wounded A A A I shall miss your valuable help very much A A A my best wishes for your recovery. French. Captain W. T. Payne-Gallwey, M.V.O., who was in charge of the machine-guns in the First Brigade, was reported missing. Orders were given to retire, and the Battalion quietly withdrew in single file of half-platoons, covered by a rear party from No. 2 Company. The enemy, as already stated, had been thrown into
  • 76. hopeless confusion in the wood, and, in spite of a prodigious amount of shouting and blowing of horns, could not get forward. Some three hours later a second engagement was fought on the other side of Villers-Cotterêts. The 4th Brigade retired through the 6th Brigade, which with the field artillery had taken up a position at the edge of another wood. The enemy's first shells came over as the 4th Brigade moved into the wood. The British guns succeeded in keeping the Germans at bay, but were only got away with the utmost difficulty and some loss. Having borne the brunt of the fighting, the 4th Brigade had necessarily suffered heavy casualties. The 2nd Battalion Grenadiers lost 4 officers and 160 men, while the Irish Guards lost 4 officers and the Coldstream 7, as well as a large number of men. Two exceptionally good officers in the Irish Guards were killed—Colonel the Hon. G. Morris and Major H. F. Crichton. The latter served in the Grenadiers for some years before exchanging into the Irish Guards.[1] On emerging once more into open country, the 2nd Battalion Grenadiers was sent off to march to Boursonne, which it reached about 4 P.M. Two companies of the 2nd Battalion Coldstream were ordered back to support the 6th Brigade, which was now protecting the retreat of the guns; but they were not wanted after all, and were sent back to Boursonne after a fruitless journey. Then General Monro rode up, and ordered the 2nd Battalion Grenadiers to take up a rear- guard position about Boursonne, to cover the retirement of the 6th Brigade. Meanwhile, the Brigade Headquarters, the Irish Guards, and the 3rd Battalion Coldstream went on to Betz. When the 6th Brigade had passed through, the 2nd Battalion Grenadiers and 2nd Battalion Coldstream retired to Thury. Unfortunately no orders had been given them to go to Betz, and through following the 6th Brigade these two battalions missed the guide whom Battalion Headquarters had sent to meet them. Once more the men were absolutely dead beat. They had had nothing to eat since tea the day before, but when the matter of food was
  • 77. Sept. 2. inquired into it was found that all the supplies had gone on to Betz. This was at 11 o'clock at night, and it looked as if the men would have to bivouac foodless by the roadside. Heroic measures were called for, and Major Jeffreys decided to brush aside the ordinary procedure and shortcircuit the usual channels of communication by going straight to the Divisional Commander, General Monro. He was instantly successful. On learning of the sad plight of the Battalion, General Monro undertook to supply it with food. He ordered his D.A.Q.M.G. to take the Battalion to his supply depot, and Major Jeffreys went back and fell in his weary men. With the promise of a meal ahead they responded gamely, and marched off to La Villeneuve, the place indicated by the General, where rations of bully-beef, bread, and cheese were soon distributed. Then the men were allowed two hours' sleep by way of a night's rest after one of the longest and most strenuous days they had ever had. They were more fortunate, though, than the men of the 2nd Battalion Coldstream Guards, who did not even manage to get any food that night, and who had to snatch what sleep they could lying down in the streets of Thury. At 2 A.M. the Battalion marched off again— still retiring—through Antilly to Betz, where it was joined by No. 1 Company and 45 men of No. 4 under Lieutenant Stocks. Thence by Montrolle to Reez, where a halt was made for water, and on to Puisieux. Here the men had a late breakfast, and then, in stifling heat, continued their march, with constant halts, through La Chaussée and Barcy to Meaux. They reached this village at 4 P.M., and, their long day's journey ended, they were refreshed by a bathe in the Ourcq Canal. This march was almost the hardest of the whole retreat, but, in spite of everything, the Battalion marched on, with scarcely a man out of the ranks, although the number of men who fell out in other regiments was by no means small.
  • 78. Sept. 3. Sept. 4. Undoubtedly the men were by now beginning to feel the strain of this interminable retirement. However footsore and weary they may be, British troops will always respond when called upon to advance. But to ask them to make a special effort when retreating is quite another thing, even with the most highly disciplined. Besides, they were quite unable to see the necessity of it all. There had been no pitched battle, no defeat—in fact, whenever they had had a chance they had inflicted enormous losses on the enemy and driven him back. Of course they had seen no newspapers, and had no way of picking up any real idea of what was going on in France. Next morning at 7 o'clock the march was resumed eastwards, and the Division crossed the Marne at Trilport, blowing the bridges up after them. This new direction was the result of the Germans moving along the north bank of the Marne, which they crossed near Sammeron. Then the Battalion moved southward again, through Montceaux and Forêt du Mans to Pierre Levée, where it bivouacked. The men had expected a rest on September 4, but the order soon arrived for the Brigade to continue the retirement. No. 3 Company of the 2nd Battalion Grenadiers under Captain Gosselin, and No. 4 Company under Captain Symes-Thompson, were sent out on outpost duty. In the morning the Brigade marched to Les Laquais, where trenches were dug, joining up with the 5th and 6th Brigades on the right. At 5 P.M. the enemy shelled the right of the line, and at dusk the Brigade withdrew. It picked up No. 3 Company at Grande Loge Farm, and marched through Maisoncelles and Rouilly le Fay to Le Bertrand, where it bivouacked for the night. Meanwhile Major Lord Bernard Lennox was despatched to Coulommiers to find the first draft that had been sent out from home—90 men under Captain Ridley. They arrived about midday after a train journey of thirty-six hours—they had been all round the country, constantly receiving fresh orders to go to different places. Lord Bernard Lennox had been instructed to remain at Coulommiers,
  • 79. Sept. 5. Sept. 6. but when he found the First Division retiring through the town all the afternoon, he decided to strike off westward with the new draft in search of the Battalion. This plan succeeded, and he found it about midnight. It was a sadly tattered, unshaven, footsore body of men that marched at 3 o'clock next morning through La Celle and Malmaison Farm to Fontenay, where they went into billets. No Londoner seeing them would have guessed that these were the same smart Grenadiers whom he had often admired on the King's Guard. But if their looks were gone, their spirit was indomitable as ever. The Germans seem to have been genuinely under the delusion that by this time the long retreat had reduced the British Army, always "contemptible," to a mere spiritless mob, which it was no longer necessary to take into calculation in developing their plan of campaign. They little knew the British soldier. So far the 2nd Battalion Grenadiers had had no chance of showing its quality; it had just been marched off its feet from the start—in the wrong direction. But, in spite of all the men had gone through, they were ready at any moment to turn and fight like lions when they were allowed to. And now at last the moment was close at hand. To their joyful surprise the officers of the Battalion found, on the morning of September 6, that the direction had been changed, and that an advance was to be made eastward against the German flank. At first it was thought that this meant the beginning of an offensive-defensive, the German attack having failed; but in reality, of course, the change was a much bigger one even than this. The French reserves were now available, and the Germans' greatest asset, superior numbers, was lost to them. And so a new phase of the campaign began to develop. On the 6th Lieut.-Colonel Corry resumed the command of the Battalion, and Lieut.-Colonel G. Feilding took command of the Brigade.
  • 80. CHAPTER IV THE BATTLE OF THE MARNE (2ND BATTALION) The German General Staff at this juncture realised that a retreating army is not necessarily a beaten one. For the last ten days, with their maps spread before them, they had had the satisfaction of moving the pins and flags representing their forces continually and rapidly nearer and nearer Paris. But if the French Army—the British Army, they thought, could be safely ignored—were to succeed in escaping south, it would remain a constant menace. It might even interfere with the Emperor's spectacular entry into Paris, every detail of which had been sketched out beforehand by the officials, whose business it was to stage-manage all the theatrical pageantry of their Imperial master's movements. So a big coup was wanted—a smashing blow at the French. If the centre of the French line could be pierced by the combined efforts of Von Hausen's, the Duke of Würtemberg's, and the Crown Prince's armies, and if simultaneously Von Kluck's army, which had reached Senlis, and was only twenty-five miles from Paris, could execute a swift movement to the south-east, the Fifth French Army would be caught in a vice. This strategic plan really menaced the whole of the interior of France, and had it succeeded might have resulted in her downfall. In all these calculations of the German Staff it appears to have been assumed that the British Army was practically out of action, and that whatever remained of it had in all probability been sent to reinforce the weak spot at Bar-le-Duc. To accomplish his decisive stroke, Von Kluck had to execute that most dangerous of all manoeuvres, a flank march with the object of
  • 81. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com