SlideShare a Scribd company logo
Instant Ebook Access, One Click Away – Begin at ebookgate.com
C 20 for Programmers 3rd Edition P. Deitel
https://ebookgate.com/product/c-20-for-programmers-3rd-
edition-p-deitel/
OR CLICK BUTTON
DOWLOAD EBOOK
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Click here to visit ebookgate.com and download ebook now
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.
Other documents randomly have
different content
though it might not have been a source of anxiety (12). O king,
perhaps thinking that my arrival was not conducive to your well-
being, you did not offer hospitality to such an unworthy person (13).
O you of large arms, why should you not give away your daughter
(in Swayamvara) for the very sin of my arrival here. Leaving me
aside, do you confer your daughter on a good husband (14). Manu
and other leading Law-givers have ordained that he who puts
obstacles in the way of a maiden, wastes himself in hell (15). O king,
for this, I did not enter into the assembly-hall and accept hospitality
(16). O king, when possessed greatly by bashfulness, I prayed for
giving rest to my followers in the city of Vidarbha, Kaishika, ever
fond of guests, offered us proper hospitality. I too, in the company
of Garuda, am living here as in the city of gods" (17–18).
Vaishampāyana said:—When Krishna, effulgent like burning fire,
showered these thunder-like words, king Bhishmaka, sprinkling him
with sweet words, consoled him (19).
Bhishmaka said:—"Be thou propitiated, O Lord of the celestial
region. Do thou forgive me, O Lord of the land of mortals. I am
possessed by the darkness of ignorance; do thou give me eyes of
wisdom (20). We are men of perverse understanding, gifted with
fleshy eyes. Therefore whatever we do without judging is not
accomplished (21). However we have obtained thee now who art the
God of gods. May my vision grow wise and works be accomplished
(22). The wise, like great commanders, render fruitful
unaccomplished works by the discernment of moral laws (23).
Having obtained thy shelter, I do not entertain any fear. Listen to
what I wish to accomplish now (24). O king of gods, I do not wish to
allow my daughter to hold her Swayamvara lest she may choose
another. Be thou propitiated with me, O Lord of celestials. Do not be
angry with me" (25).
Krishna said:—"O king of great intelligence, O sinless one, I do
not perceive the utility of your sayings. Who can adjust whether you
will give away your daughter or not (26). O king, the goddess-like
form of Rukshmini has brought me to this place. But I should not
say that you should give her to me and not to anybody else (27).
When in the days of yore the gods assembled on the summit of the
mount Sumeru for incarnating their portions they said to her: 'O
thou of spacious hip, do thou with thy husband go to the world of
men. And having been born in the house of Bhishmaka in the city of
Kundina, be thou united with Keshava (28–29)'. I tell you this plainly,
O king; do what ever you think proper after due consideration (30).
O king, truly your daughter Rukshmini is not a woman; she is the
very goddess Sree. For some object and at the words of Brahmā she
is born (as a woman) (31). She should not be given away in a
Swayamvara where all the kings will be assembled. She must remain
alone, and inviting one bride groom, you should confer her on him.
It will be thus performing a Kshatriya's duties (32). O king, you
cannot give away Lakshmi in a Swayamvara. Selecting a good
bridegroom, you should give her away according to proper religious
rites (33). In order to put impediments in Swayamvara Vinata's son
has been despatched by the king of gods and has come to the city
of Kundina (34). I too have come here to witness this Swayamvara
festivity of the kings and your daughter, the beautiful Kamala
without lotuses (35). Your saying before me 'Forgive me' is
considered by me as proper. And I do not find any folly in it, O king
(36). O lord, I have already been pacified. Know me as conciliated
since I have come to your territory in a gentle form (37). O king, to
cast off one's shortcomings is forgiveness and it is endued with
many virtues. So, how can the mind of one like myself be possessed
by the sin of non-forgiveness (38). How can sin, O king, be attached
to you who are moral, truthful and born in a family possessing the
quality of goodness (39). Know me conciliated particularly as I have
come with my army, for with them I never confront my enemies
(40). When I cherish no forgiveness in my heart I go on the back of
my carrier, Garuda, the foremost of birds, with weapons effulgent
like the sun in my hand (41), O king, you are of the same age with
my father and are therefore adorable unto me like him. Behaving
with me, as a father treats his son, govern your kingdom well (42).
How can that sin, which resides in the heart of a coward, find room
in the heart of a pure-souled hero (43)? Know my conduct as pure
as a father's feeling towards his son. Treating us with hospitality,
these two kings of Vidarbha have given us their kingdom. By the
fruit of this gift their ancestral manes of ten generations upwards
have gone to the celestial region (44-45) And ten succeeding
generations too of their royal line from son to grandson will also
repair to the celestial region (46). And they two, enjoying their
kingdom for many long years, without any thorns, will attain to
emancipation when they will wish it (47). And those noble kings,
who were present at my Abhisheka, will in time repair to the celestial
region (40). O king, may you fare well! I shall now with Vinatā's son
go to the charming city of Mathura protected by the king Bhoja"
(49).
Vaishampāyana said:—Saying this to the king Bhishmaka,
welcoming all other kings and issuing out of the Hall with Kratha and
Kaishika, the lords of Vidarbha, Krishna, the foremost of gods and
Yadus, went to his car (50). Beholding the departure of Keshava, the
faces of the royal saint Bhishmaka and of other kings were stricken
with sorrow (51). At that time beholding the prime and self-sprung
Krishna, having eyes like red lotuses, thousand feet, thousand eyes,
thousand arms, thousand lustrous crowns, thousand heads, adorned
with celestial garlands, raiments, scents, unguents and ornaments,
holding uplifted celestial weapons and having three eyes of the sun,
moon and fire, the king Bhishmaka bowed unto him and began to
eulogise his glories, with his body, mind and speech (52–55).
Bhishmaka said:—O God of gods, O Nārāyana, O Parāyana, thou
hast no origin or destruction. Thou art the eternal prime Deity, I bow
unto thee (56). Thou art the self-sprung Deity, art identical with the
universe, lotus navelled, hast clotted hairs, dost hold a staff and art
of coppery hue. I bow unto thee (57). Thou art Hansa, the discus,
Vaikuntha, unborn and the great Atman. I bow unto thee (58). Thou
art Yogin, the existent and non-existent, the ancient Purusha, the
foremost of Purushas, above three-fold qualities. I bow unto thee
(59). O Lord, O foremost of the celestials, that alone art the lord of
all the worlds and the lord of those who have acquired a know
fledge of the soul. I am thy votary. Be thou propitiated and confer
on me a boon (60).
Vaishampāyana said:—Having thus chanted the glories of the
great God Krishna in the presence of the king, Bhishmaka made a
present of precious gems, pearls, and plates of Vaidurja unto him.
Thereupon he saluted in this way the highly powerful son of Vinatā
too (61–62).
Bhishmaka said:—I bow unto that celestial bird, the son of
Kashya endued with the velocity of the wind who can assume
various forms at will (63).
Vaishampāyana said:—Having thus chanted, in brief, the glories
of Vinatā's son Bhismaka offered him various sorts of most excellent
raiment. After the lotus-eyed Krishna, the younger brother of
Vāsava, on taking leave, had departed all the kings followed him.
Having thus received honors, taken farewell of all the kings, placed
Vinatā's son the foremost of birds, of a gentle form before him, been
encircled by huge cars, and lighted up all the quarters the energetic
Krishna set out for Mathurā. At that time there arose a great tumult
consisting of the sound of bugles, trumpets, conches, the hissing of
the serpents, the neighing of horses, and the rattle of the wheels of
the cars resembling the muttering of huge clouds.
After the departure of the highly powerful Krishna the gods
repaired to the celestial region with that assembly hall and the most
excellent seat. Encircled by their huge four-fold forces the kings
followed Janārddana, a distance of two miles and afterwards at his
command returned to Swayamvara (64–69).
CHAPTER CIX. JARASANDHA'S PROPOSAL TO
INVITE KALAYAVANA.
Vaishampayana said:—After the departure of Vasudeva's son the
kings, who had their limbs embellished with ornaments and who
were anxious to go to their respective kingdoms, returned to the
assembly-hall of Bhishmaka in order to inform (Jarāsandha of their
intention) (1). Thereupon king Bhishmaka, the foremost of kings and
well-read in moral laws, said to the kings, effulgent like the sun and
the moon and seated at ease on beautiful seats (2). "O ye kings, you
all know the calamity that will befall the Swayamvara. Do you forgive
me for the fruit that is the outcome of my misconduct" (3).
Vaishampāyana said:—Having thus addressed and welcomed
duly all the kings, (the king) sent away all the monarchs of Central
India and of the East, West and Northern Provinces. Having honored
the king Bhishmaka duly in return, those kings, the foremost of men
and mighty car-warriors, went away delightedly. Jarāsandha,
Sunitha, the energetic Dantavakra, the king of Soubha, the king
Mahākurma, Kaishika, all the leading kings of the Pravara race, the
royal saint Venudāri, the king of Kashmira all those and other kings
of the Deccan remained by Bhishmaka desirous of listening to the
mystery.
O monarch, beholding these kings waiting there the powerful
king Bhishmaka, with an affectionate heart and grave and cool voice,
said to them moral words relating to three-fold objects and
embellished with figures.
Bhishmaka said:—"O ye kings, I have acted thus in pursuance of
moral words given vent to by you; you should forgive me for we
must always abide by moral laws" (4-12).
Vaishampāyana said:—Having thus expressed himself in the
concourse of kings, the king Bhishmaka, well-versed in moral laws,
again said aiming at his son (13).
Bhishmaka said:—Observing the movements of my son my eyes
are agitated with fear; I consider all now as mere boys. He (Krishna)
alone is the foremost of Purushas (14). He, the very incarnation of
glory, the foremost of the illustrious, the partaker of fame and
powerful, has established great fame and the might of his arms in
this land of mortals (15). Blessed is Devaki, the foremost of damsels
who has conceived as her son the lotus-eyed Krishna, identical with
the sum total of beauty, the greatest of all in the three worlds, and
adored of all the immortals and who has seen his lotus countenance
with her eyes full of affection (16-17.)
Vaishampāyana said:—When the king Bhishmaka gave vent to
these words again and again in the midst of the assembled kings the
highly effulgent king Shalya said in sweet words (18).
Shalya said:—O slayer of thy enemies, O lord of kings, do not
lament for thy son. The Kshatriyas meet either with success or
defeat in battle (19). This is the inevitable course and eternal
religion of the mortals. Save Baladeva and Krishna what third person
can withstand thy highly powerful son in battle? Taking up his bow
thy mighty-armed son is alone capable of withstanding the car-
warriors and great heroes of the enemy in battle. When by the might
of his arms he handles the Bhārgava weapons, difficult of being used
even by the celestials what man is capable of bearing it? This Eternal
Purusha Krishna is without birth or death (20-23). In this land of
mortals even the holder of trident (Siva) cannot defeat him. O
Emperor, thy son is well-versed in the true meaning of all the
Shastras (24). Knowing Keshava as Ishāna he did not engage in fight
with him. It is not that there is none who can defeat him (25).
Kālayavana is incapable of being slain by Keshava. With a view to
have a son the great Muni Gārgya adored Rudra for twelve years
living on powdered iron and practising dreadful and highly difficult
penances. Thereat pleased when Shankara offered him a boon
Gārgya prayed for a son whom the kings of Mathurā would not be
able to slay. Rudra granted him the boon, saying 'so be it' (26-28).
Thus by virtue of Rudra's boon, Gārgya's son Kālayavana is
unslayable by the kings of Mathura in the battle-field and especially
in the city of Mathurā (29). Though Krishna is highly powerful
amongst the princes of Mathura still if he comes to battle and fights
with him he will be able to defeat him (30). O kings, if you accept
my words as becoming and sound, send an emissary to the capital
of the king of Yavanas (33).
Vaishampāyana said:—Hearing the words of the highly powerful
Shalya the king of Soubha all the leading kings were delighted and
said "We will do it" (32). Hearing their words and recollecting those
of Brahmā the Emperor Jarāsandha lost heart and said (33).
Jarasandha said:—Alas! formerly, assailed by the fear of a
foreign king, all the Chiefs, seeking refuge with me, used to get back
their lost kingdoms, servants, army and conveyances (34). Now, on
account of their bad feelings towards their lord, they, like unto a
damsel, coming in contact with a stranger, are now exciting me to
seek another's shelter (35). Alas! even when I, afraid of Krishna, am
constrained to seek refuge with another, Destiny alone is powerful.
And by no means can any one overcome it (36). O ye kings, it is
better for me to die than to seek helplessly the protection of another
(king). I shall not therefore seek refuge with any body else (37). I
shall give him battle who has been pointed out as my Death by the
invisible words, may he be Krishna, or Baladeva, or a man, or some
one amongst the immortals (38). Even this is my firm resolution and
such is the conduct of a worthy person. I shall not act against it
seeking another's protection (39). Even if you be all well disposed he
(Krishna) may destroy you all. For your protection I shall send an
envoy to him (40), O kings, the messenger should so proceed by the
etherial way that Krishna may not put in any impediment. Do ye find
out such a person who can go in this way (41). This effulgent king of
Soubha is gifted with the prowess of fire, the sun and the moon. In
a sunny car let him proceed to the capital of Yavana (42). Let him
approach the king of Yavanas as our envoy and communicate to him
our quarrel with Krishna. Let him try to bring him over to this
assemblage of Chiefs (43).
Vaishampāyana said:—Having thus expressed himself the
Emperor Jarāsandha again said to the powerful king of Soubha:
—"Do thou depart, O giver of honors and help all these Chiefs (44).
Use such tactics that the king of Yavanas may proceed and vanquish
Krishna and we may be pleased" (45).
Having thus commanded all and worshipped Bhishmaka duly
the Emperor, encircled by his own army, set out for his city (46).
Shalya, too, the foremost of kings, having honored all duly, set out
by the etherial way in a car, coursing like air (47). Following
Jarāsandha to some distance the Deccan Chiefs repaired to their
respective cities (48). Thinking of his own evil conduct, of Krathā,
Kaishika and Krishna, the king Bhishmaka, along with his own son,
entered into his Palace (49). On account of the discomfiture of the
kings consequent upon Krishna's arrival and the termination of the
Swayamvara the chaste and wise Rukshmini approached her friends
and with her face bent down in shame said:—"I tell you truly, I do
not wish to be the spouse of any body else save Krishna having lotus
eyes" (50-51).
CHAPTER CX. SHALYA MEETS KALAYAVANA.
Vaishampayana said:—Kālayavana, the king of Yavanas, was highly
powerful and used to govern the inhabitants of his city in pursuance
of royal duties (1). He was wise, conversant with three Vargas,274
proficient in six Gunas275
innocent of sevenfold calamities,276
endued
with all accomplishments, well-versed in Srutis, pious, truthful, a
master of his senses, acquainted with the rules of war, an expert in
capturing forts, heroic, of great strength and used to honor his
ministers. One day encircled by his ministers he was seated at ease
and the learned and intelligent Yavanas, discoursing amongst
themselves on various celestial themes were adoring him (2–5). In
the meantime there blew delightful, but exciting, cold and fragrant
wind. Thereat the assembled Yavanas and the king Kālayavana were
all worked up and thought "Whence it has come?" Thereupon they
saw a car coming from the south. It was golden and white, lighted
up with the lustre of jewels, adorned with celestial flags and
pennons, drawn by horses fleet like the mind or air, adorned with
tiger-skins, a terror to the enemies, the enhancer of joy to the
friends, constructed by the celestial Architect, effulgent like the sun,
the grinder of others' cars and embellished with jems like the rays of
the sun and moon. The powerful and beautiful king of Soubha was
seated thereon. Delighted greatly at seeing his friend the mighty-
armed king of Yavanas, the foremost of speakers, repeatedly sent
for Arghya and water to wash feet. And rising up from his throne
and with Arghya in his hands he went out and waited at the landing
stair of the car. Be holding the king Kālayavana, powerful like Sakra
the highly energetic Shalya was greatly delighted, got down alone
from the chariot with a confident heart and joyously entered into the
Palace of Yavana for seeing his friend. Observing arghya in the
hands of the king of Yavanas, Shalya, the foremost of kings, said in
sweet words:—"O thou of great effulgence, I am not now worthy of
arghya. I am now an envoy of the kings and have been despatched
to thee by the intelligent Jarāsandha. I therefore do not deserve
arghya from the kings" (5–18).
Kalayavana said:—"O you of large-arms, I know that you have
been despatched here as an envoy by the king of Magadha for the
behoof of kings (19). O intelligent king, I adore you duly with water
to wash feet, seat and various other means of welcome because you
have been sent here by the entire circle of kings. By adoring you, O
king, I shall worship the entire host of kings and by honoring you all
of them will be honored. Therefore, O king, sit with me on this
throne" (20–21).
Vaishampāyana said:—Thereupon shaking hands with each
other and enquiring of their mutual welfare those two kings sat at
ease on the sacred throne (92).
Kalayavana said:—What has become impossible to him,
depending on the might of whose arms you kings are all living
without any anxiety as the gods do under the protection of Sachi's
lord, that he has sent you to me. Tell me, truly, O king, what
mandate, the powerful king of Magadha has issued to me. Even if it
be very difficult I shall carry out his command (23-24).
Shalya said:—O king of Yavanas, hear I shall describe at length
what the king of Magadha has deputed me to communicate to you
(25).
Jarasandha said:—The highly irrepressable Krishna has been
oppressing the world from his very birth. Informed of his wicked
deeds I attempted to slay him (26). Accompanied by a number of
kings along with their four-fold forces and conveyances I besieged
the mount Gomanta with a huge army (27). And there listening to
the highly sensible words of the king of Chedi I set fire to that best
of mountains for their (Rāma and Krishna's) destruction (28).
Beholding that fire consisting of hundreds and thousands of flames
and resembling the fire of dissolution, Rāma, holding the golden hilt
of a sword, leaped down from the mountain summit in the midst of
the ocean-like army of the kings. And that highly irrepressible one
began to kill the car-warriors, the infantry and cavalry (30). He
moved about like a serpent; and catching elephants, horses and
soldiers with his plough-share he grinded them with his mace (31).
In that battle-field abounding in hundreds of kings that highly
energetic Rāma, endued with the prowess of the sun, ranging in
various ways like the setting sun, destroyed elephants, with
elephants, car-warriors with cars, and the cavalry with horses (32-
33). After Rāma, the highly powerful and energetic Yadu hero,
Krishna, taking up his discus effulgent like the sun, and his black iron
club, forcibly leaped down in the midst of the enemie's army
agitating the mountain with the force of his feet as a lion attacks the
poor deer (34–35). O king, at that time whirling and bathed with
shower that mountain extinguished the fire and entered into the
earth as if dancing (36). Jumping down from that burning mountain
Janārddana with his hand holding the discus began to destroy our
army (37). Whirling his huge discus and throwing all down with his
club he began to grind men, elephants and horses with his mace
(38). Then with the fire of discus and plough-share begotten by their
anger that huge army, protected by sun-like kings, was consumed
(39). Within a moment our army consisting of men, elephants horses
infantry and flags, was consumed by those two foot soldiers (40).
O king, beholding that army distressed by the fear of the fire of
discus and routed, I, encircled by a huge collection of cars, engaged
in battle. And Keshava's brother the heroic and valiant Baladeva, the
destroyer of Bala, stood before me with a club in his hand (41–42).
Having slain the twelve Akshouhinis of soldiers and cast off his
plough-share and mace Sounanda, that leonine hero pursued me
with his club (43). O king, having thrown the club on me with a
force like that of the fall of a thunder-bolt he again stood manfully
on the ground (44). Then like unto Kārtikeya at the time of the
destruction of Krounch, he, with his two large eyes, as if consumed
me, looking at my joints (45). O king of Yavanas, beholding such a
form of Baladeva, what person, having hopes of life, can stand
before him in the battle-field (46)? When he stood before him
holding up that terrible club resembling the rod of the Regent of the
dead and whirling it along with his plough-share Brahmā, the grand-
father of all, filling the welkin with his invisible voice grave as the
muttering of clouds, said:—"O sinless Rāma, do not strike (him); O
holder of plough-share, it has been destined that he shall not meet
with his death from any other person." Hearing with my own ears
those words given vent to by the Grand-father I was filled with
anxiety and returned from the battle-field (47–50).
O king, for this reason, and for the behoof of the kings, I
communicated this incident to you. Hearing this you should do what
you think proper in pursuance of my words (51). Desirous of having
a son your father propitiated Sankara, the god of gods with hard
austerities and obtained you as his son unslayable by the princes of
Mathurā (52). Fasting and feeding on powdered iron for twelve years
the great Muni Gārgya propitiated the great god Siva, on whose
lotus feet even the gods and Asuras meditate and therefore obtained
his wished-for prosperity in the person of yourself (53). By virtue of
the asceticism of the ascetic Gārgya and of the power of Mahādeva
carrying the emblem of a crescent forsooth, shall Janārddana meet
with his death as the dews are dried up by the rays of the sun (54),
O king, thus requested by the kings, be up and doing and march for
vanquishing Krishna. And entering the city of Mathurā with your
army establish your glory there (55). Vasudeva's son is a native of
Mathurā and Baladeva is his brother. If you go to the city of Mathurā
you will be able to defeat them in battle (56).
Shalya said:—O king, I have thus communicated to you, the
message entrusted to me by the Emperor Jarāsandha for the behoof
of the kings. Do you now undertake what is proper and conducive to
your well-being after consulting duly with your ministers (57).
[274] Three conditions of a king or state; prosperity, evenness or
decay or loss, gain and equality.
[275] The six acts of a king in his military character, or peace,
war, marching, halting, sowing, dissension, seeking
potection.
[276] The seven calamities are gambling, sleeping in a day,
calumny, whoring, playing, idle roaming, drinking and
hunting.
CHAPTER CXI. KALAYAVANA AGREES TO KILL
KRISHNA.
Vaishampayana said:—After the king Shalya, as directed by the
Emperor Jarāsandha had said this Kālayavana, the king of Yavanas,
with great delight said (1).
Kalayavana said:—Oh! highly honored and blessed I am; and my
life is crowned with success since numberless kings have requested
me for vanquishing Krishna (2). The kings have appointed me in the
work of subduing Krishna who is invincible in the three worlds, even
unto gods and Asuras. And they have blessed me so that I will
achieve victory (3). While the kings, with delighted hearts, have
declared my victory I shall, by the very pouring of their water-like
words, achieve success (4). Whatever it may be, I shall carry out the
command of the Emperor Jarasandha issued at the request of the
kings. Even my discomfiture in it will be, tantamount to my success
(5). O king, to-day, the day and the stars are auspicious and in this
auspicious moment I shall even to-day start for Mathurā for
defeating Keshava in the battle-field (6).
Vaishampāyana said:—Having thus addressed the powerful
Shalya the king of Soubha, the lord of Yavanas honored him duly
with highly precious jems and dresses (7). Afterwards for acquiring
unstinted blessings he gave away various riches to his guest and the
Brāhmanas and duly offered libations to fire. Then after the
performance of benedictory rites he set out with his army for
vanquishing Janārddana (8–9). O foremost of Bharatas, king Shālya
too, with his desire fully achieved, embraced the lord of Yavanas and
set out with a delighted heart for his own city (10).
CHAPTER CXII. UGRASENA RECEIVES
KRISHNA.
Janamejaya said:—O Brahman, when the Lord Krishna, endued with
Sakra's prowess, set out from the city of Bidarbha he did not ride the
highly powerful son of Vinatā, Garuda; why did he then take him
away with him? And what did Vinatā's son do? O great Muni, I am
filled with great curiosity in this; do thou unfold the mystery (1–2).
Vaishampāyana said:—O king, listen to the work, difficult of
being done by men, which the highly effulgent son of Vinatā
performed after his departure from the city of Bidarbha (3). O lord,
before his departure to the city of Mathurā when Janārddana, the
god of gods, said before the assembled kings, "I shall repair to the
charming city of Mathura governed by the Bhoja king" the beautiful
and intelligent son of Vinatā thought for a considerable time, and
then saluting Vāsudeva, after he has finished his say, said with
folded hands (4–6).
Garuda said:—"O god, I shall now proceed to Raivata's city
Kushasthali, to the charming mount Raivata and the adjacent forest
thereto resembling the garden of Nandana (7).
"The Rākshasas have abandoned the charming city of
Kushasthali. It is situate at the base of the Raivata mountain and on
the bank of the great ocean. It abounds in trees decorated with
filaments of flowers, in groves and creepers. It is scattered with
elephants and serpents, and inhabited by bear, monkeys, boars,
buffaloes and deer. I shall perfectly examine (that place) and see if it
is worthy of thy habitation. O lord, if that extensive and charming
city is fitted for thy residence, I shall remove all the thorns and come
back to thee" (8-10).
Vaishampāyana said:—Having thus expressed himself before
Janārddana, the king of gods, and saluted him the powerful lord of
birds set out towards the western direction (11). And when Krishna
too, with the Yadavas, entered into the beautiful city of Mathurā,
Ugrasena came out of the city with dancing girls and citizens and
honored the victorious Krishna (12).
Janamejaya said:—What did the mighty-armed Emperor
Ugrasena do when he heard of Krishna's installation by the
numberless kings (13)?
Vaishampāyana said:—Hearing of Krishna’s installation as the
Emperor by numberless kings, of Indra's making peace with him
through his envoy Chitrangada, of the apportionment of wealth,
each king being entitled to a lakh, each emperor to a Arvuda and
each ordinary men to ten, and that every one, who came there, did
not go away empty handed and that the graceful lord of Nidhis,
Sanka, commanded by the gods, distributed wealth after Krishna's
heart, from his own men and other persons informed of people's
conduct, Ugrasena offered a great puja at the temples of the
tutelary deities. The two sides of the gate of Vasudeva's house were
decorated with flags, pennons and garlands. He also decorated with
flags Kansa’s assembly hall Suprabhā adorned with various sheets of
cloth (14-20). The doors of the sitting-room of the Emperor Krishna
in Gopura were pasted with ambrosia by the king (21). There was
dancing and music on all sides. The city was decorated with flags,
garlands of wild flowers and jars full of water (22). The king
sprinkled sandal water in all the high-ways and spread sheets of
cloth on the ground (23). On both sides of the roads incense was
kept in vessels and continually burnt with Aguru, molass and various
other articles (24). The elderly women began to sing benedictory
hymns and youthful damsels moved about anxiously in their
respective houses (25).
Having thus commenced the festivity in the city the Emperor
Ugrasena repaired to Ugrasena's Palace and after communicating to
him the pleasant news and consulting with Rāma went to the car. O
king, in the meantime the great sound of the conch-shell
Pānchajanya was heard. Hearing that sound of the conch the entire
city of Mathurā, with their women, boys, elderly men, panegyrists,
songsters, and accompanied by a huge army, issued out placing
Rāma before them. Ugrasena himself carried arghya and water for
washing feet for Krishna (26–29).
After going over to some distance and coming within the view of
Vāsudeva the Emperor Ugrasena desired to proceed on foot and
accordingly got down from his white car (30). And beholding Hari,
the king of gods, seated on a charming car adorned with celestial
jewels he, in words suppressed with joy, said to the lotus-eyed Rāma
the slayer of his enemy's army. Krishna was adorned with ornaments
set with jewels, was shining like the sun on account of the garland
of wild flowers decorating his breast, was accompanied by fans,
umbrellas and flags with the emblems of Garuda painted thereon,
embellished with all the marks of royalty and endued with the
beauty of the rising sun (31–34).
(Ugrasena said):—"O great one, it does not behove me to
proceed on car after this. Thinking this I have got down. Do thou go
on the car (35). Coming to Mathurā in the disguise of Keshava
Vishnu has manifested himself as the king of gods in the ocean-like
assemblage of the kings. I therefore wish to chant his glories
properly." The highly effulgent elder brother of Krishna (then) replied
to the king (saying) (36–37):
"O king, it is not proper to chant the glories of that best of kings
at the time of his going. Without it Janārddana is pleased with you.
What is the use of hymning him who is himself propitiated? Your
visit is identical with your chanting of his glories. While Krishna,
although he has acquired the dignity of the Lord Paramount, is
coming to your house, what is the use of praising him with celestial
and super-human hymns?" Thus conversing with each other they
went to Keshava (38–40).
Beholding the king Ugrasena approach with arghya in his hands
Krishna, the foremost of orators, stopped his car and said:—"O king
of Mathurā, while I have installed you, declaring, 'Be you the lord of
Mathura' it does not behove me to make it otherwise. O king, you
should not offer me arghya and water for washing my feet and
rinsing my mouth. This is my heart-felt desire (41-43). O king,
informed of your intention I say that you are the king of Mathura. Do
not make it otherwise. O king, I will confer upon you your proper
share in the land and gift. As I did with the other kings I had kept
your share in reserve beforehand, one hundred thousandth portion
without any ornaments or raiment. O king, get upon your white car
adorned with gold, umbrella, fans, flags and celestial ornaments.
And wearing your crown of sunny lustre govern the city of Mathurā,
delightedly with your sons and grand-sons, defeat your enemies and
multiply the Bhoja race. The king of gods, the holder of thunder-bolt
sent, for Ananta and Shouri, celestial ornaments and raiments. From
the thousand jars of gold coins reserved for the citizens of Mathurā
in that ceremony of installation the king of gods has ordered that
one thousand should be given to each of the panegyrists and bards,
one hundred to each old man, prostitute and other men and ten
thousand to each of the Yādavas, Vikadru and others who live with
the king Ugrasena (44–52)".
Vaishampāyana said:—Having thus honored the Emperor
Ugrasena in the presence of all the soldiers Janārddana, with great
delight, entered the city of Mathurā (53). On account of the celestial
ornaments, garlands, raiments and unguents it appeared as if he
was living in the city of the celestials encircled by gods (54). Like
unto the muttering of clouds there arose a great tumult consisting of
the sound of bugles and trumpets, blare of conches, the noise of
elephants, the neighing of horses, the leonine shouts of the heroes
and rattle of car-wheels (55-56). The panegyrists began to sing his
praises and the subjects to salute him with numberless presents. At
this Hari was not the least surprised (57). He was high-minded by
nature, shorn of egoism and has seen a greater display than this
beforehand. And for this he was not filled with surprise (58).
Beholding Mādhava's arrival who was shining in the lustre of his own
person effulgent like the sun the inhabitants of Mathurā saluted him
at every step and said (59):
"He is Nārāyāna, the abode of Shree living in the ocean of milk.
Leaving his serpent-couch he has come to the city of Mathurā (60).
Having chained Bali irrepressible unto the immortals he conferred
the soverignty of the three worlds on Vasava the wielder of thunder-
bolt (61). Having slain Kansa, the foremost of the powerful and
other Daityas this slayer of Keshi has conferred the kingdom of
Mathura on the Bhoja king (62). Not being himself installed and not
sitting on the royal throne, he, having acquired the dignity of the
Lord Paramount, has entrusted Ugrasena with the government of
Mathurā" (63).
Having heard this conversation of the citizens, the bards,
panegyrists and the poets sang, "O thou the ocean of
accomplishments, how can we, who are one tongued men, sing the
deeds begotten of thy prowess and energy (64–65). The thousand-
headed serpent-king Vāsuki, who has the intellect of a god, can,
with his two thousand tongues, to a certain extent describe thy
accomplishments (66). It is a great wonder to the kings of the earth
that a throne was sent by Indra. It never happened before nor will it
be in future (67). The descension of the assembly-hall and jars from
the celestial region has never been heard of or seen. Therefore we
consider it as a wonder (68). O Keshava, conceiving a son like thee,
the foremost of gods, Devaki, the best of damsels, has been blessed
because she, with her eyes full of affection, saw thy lotus face
adored by men and the immortals (69–70)".
Placing Ugrasena before them and listening to the conversation
regarding their praises sung by the citizens the two brothers Rāma
and Krishna arrived at the gate and the king worshipped them
repeatedly sending for arghya and water for washing feet and
rinsing mouth (71–72). Thereupon approaching Keshava's car,
saluting him with his head down and mounting on an elephant the
energetic and intelligent Ugrasena began to shower gold as the
clouds discharge their watery contents (73). Having thus showered
gold on him the beautiful Mādhava arrived at his father's house and
said to Ugrasena, the king of Mathura (74): "O lord, although I have
secured the dignity of the Lord Paramount, this throne, conferred by
the king of gods, should be kept in the king's Palace (75). Although
acquired by the strength of my own arms I do not like to come by
the assembly-hall of the king of Mathurā. O lord, I propitiate you. Do
not be offended" (76).
O king Janamejaya, at that time Vasudeva, Devaki and Rohini
were so much overwhelmed with joy that they could not give vent to
any word (77).
O king, thereupon considering the importance of time and
place, Kansa's mother, taking riches and presents of various
countries acquired by him, went to Keshava and dedicated them to
his feet. Observing it Krishna sent for Ugrasena and said in sweet
words (78–79).
Krishna said:—"It is time that has snatched away your two sons;
I have not slain them either for riches or for the kingdom of Mathurā
(80), O king of Mathura, having vanquished your enemies by the
might of my arms do you perform many sacrifices and make profuse
presents (81). O king, do you cast off your mental agony and fear
consequent upon Kansa's death. I return you these riches; do you
accept them" (82)
Having thus consoled the king, Krishna, along with Balarama,
went to his parents (83). There those two highly powerful heroes,
with heart full of joy, saluted their parents bending their heads (84).
O Janamejaya, at that time the city of Mathurā left off her own form
and as if the capital of gods came down there leaving the celestial
region (85). Beholding Vasudeva's house the citizens did not
consider it as earth but took it for the region of the celestials (86).
Having thus entered Vasudeva's house the heroic Baladeva and
Keshava dismissed Ugrasena, the king of Mathurā and his queen.
And then leaving off their arms and moving about for some time
they went through the evening rites. And then seated at ease they
conversed with one another (87-88). In the meantime there took
place a highly dreadful calamity. The clouds were scattered in the
sky, the earth and the mountains were shaken, the oceans were
agitated, the serpents were terrified and the Yadavas, trembling, fell
down on earth (89–90). Beholding them thus fallen the immoveable
Rāma and Krishna, perceived, from the flapping of the huge wings,
the approach of Garuda, the foremost of birds. And within a short
time they saw Garuda by them. Saluting them both with his head,
Vinatā's son, of a gentle form, adorned with celestial garlands and
unguents, sat on a seat (61–92). Observing the arrival of his war-like
minister, the intelligent son of Vinatā, the slayer of Madhu said: "O
thou the grinder of the enemies of the celestial army, O delight of
Vinatā's heart, O foremost of birds, O favourite of Keshava, may thy
arrival here prove auspicious" (93–94). Having thus addressed
Vinatā's son, stationed there like a very god Krishna again said to
him who was equally powerful (95).
Krishna said:—O foremost of birds, let us now go to the highly
extensive inner appartment of the Bhoja king, for there, seated at
ease we shall be able to hold counsels after our own hearts (96).
Vaishampāyana said:—When having entered the inner
appartment of the Bhoja king along with Vinatā's son, the highly
powerful Krishna and Baladeva held parley, the former said:—"O
Vinatā's son, the king Jarāsandha is unslayable by us. It has been so
ordained. Incomparable is his might and he is encircled by a huge
army and highly powerful kings. The army of the Magadha king
consists of many soldiers and so we shall not be able to consume it
even within hundred years. Therefore I tell you, O king of birds, that
it never bodes good for us to live in this city of Mathura. Even it is
my desire (97-100)".
Garuda said:—O god of gods, having saluted thee I took leave
and went to Kusathali for finding out a worthy habitation for thee
(101), O foremost of gods, having gone there and been stationed in
the welkin I reconnoitered all over that city endued with all
auspicious marks (102). That city is situate in an extensive watery
province of the ocean. It has the ocean on the east and is therefore
always cool. It is surrounded on all sides by the ocean, a mine of
every sort of jem, spread with trees conferring wished-for objects,
covered on all sides with flowers of all seasons and therefore highly
charming; it is the abode of all forms of Ashramas, satisfies every
sort of desire, is filled with men and women, is always full of
merriment, is encircled by ditches and walls, is embellished with
palaces and gates, variegated courtyards and roads, has huge doors
and gates, and various bolts and other contrivances, is adorned with
a golden wall, is filled with car-warriors, cavalry and infantry, and
with trees of various countries covered with celestial flowers and
fruits, is adorned with flags and pennons, contains big palaces,
strikes terror to the enemies, enhances the joy of the friends and is
isolated from other cities presided over by kings (103-109). O god,
there is that best of mountains Raivata resembling the garden of
Nandana. Do thou make it an ornament of thy gate (110). O
foremost of gods, that city will also be liked by thy sons. Do thou go
and live there (111). Like unto Indra's capital Amarāvati thy city will
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
Get C 20 for Programmers 3rd Edition P. Deitel free all chapters
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 from control structures through objects Eighth Edition To...
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
C 20 for Programmers 3rd Edition P. Deitel
Get C 20 for Programmers 3rd Edition P. Deitel free all chapters
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 from control structures through objects Eighth Edition To...
C++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions Manual

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

PDF
C++ How to Program 10th Edition Deitel Solutions Manual
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
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PDF
Computer Programming With C Kunal Pimparkhede
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PDF
T2
PDF
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PDF
(eBook PDF) C++ How to Program 10th Edition by Paul J. Deitel
PDF
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
PDF
(eBook PDF) C++ How to Program 10th Edition by Paul J. Deitel
PDF
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PDF
Object Oriented Programming using C++ PCIT102.pdf
C++ How to Program 10th Edition Deitel Solutions Manual
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)
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
C++ How to Program 10th Edition Deitel Solutions Manual
Computer Programming With C Kunal Pimparkhede
C++ How to Program 10th Edition Deitel Solutions Manual
T2
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
C++ How to Program 10th Edition Deitel Solutions Manual
(eBook PDF) C++ How to Program 10th Edition by Paul J. Deitel
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
(eBook PDF) C++ How to Program 10th Edition by Paul J. Deitel
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
C++ How to Program 10th Edition Deitel Solutions Manual
Object Oriented Programming using C++ PCIT102.pdf
Ad

Recently uploaded (20)

PPTX
Cell Types and Its function , kingdom of life
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Pre independence Education in Inndia.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
master seminar digital applications in india
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Sports Quiz easy sports quiz sports quiz
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
GDM (1) (1).pptx small presentation for students
Cell Types and Its function , kingdom of life
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Anesthesia in Laparoscopic Surgery in India
102 student loan defaulters named and shamed – Is someone you know on the list?
human mycosis Human fungal infections are called human mycosis..pptx
Basic Mud Logging Guide for educational purpose
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
VCE English Exam - Section C Student Revision Booklet
Pre independence Education in Inndia.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
master seminar digital applications in india
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Final Presentation General Medicine 03-08-2024.pptx
Sports Quiz easy sports quiz sports quiz
FourierSeries-QuestionsWithAnswers(Part-A).pdf
GDM (1) (1).pptx small presentation for students
Ad

C 20 for Programmers 3rd Edition P. Deitel

  • 1. Instant Ebook Access, One Click Away – Begin at ebookgate.com C 20 for Programmers 3rd Edition P. Deitel https://ebookgate.com/product/c-20-for-programmers-3rd- edition-p-deitel/ OR CLICK BUTTON DOWLOAD EBOOK Get Instant Ebook Downloads – Browse at https://ebookgate.com Click here to visit ebookgate.com and download ebook now
  • 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. Other documents randomly have different content
  • 51. though it might not have been a source of anxiety (12). O king, perhaps thinking that my arrival was not conducive to your well- being, you did not offer hospitality to such an unworthy person (13). O you of large arms, why should you not give away your daughter (in Swayamvara) for the very sin of my arrival here. Leaving me aside, do you confer your daughter on a good husband (14). Manu and other leading Law-givers have ordained that he who puts obstacles in the way of a maiden, wastes himself in hell (15). O king, for this, I did not enter into the assembly-hall and accept hospitality (16). O king, when possessed greatly by bashfulness, I prayed for giving rest to my followers in the city of Vidarbha, Kaishika, ever fond of guests, offered us proper hospitality. I too, in the company of Garuda, am living here as in the city of gods" (17–18). Vaishampāyana said:—When Krishna, effulgent like burning fire, showered these thunder-like words, king Bhishmaka, sprinkling him with sweet words, consoled him (19). Bhishmaka said:—"Be thou propitiated, O Lord of the celestial region. Do thou forgive me, O Lord of the land of mortals. I am possessed by the darkness of ignorance; do thou give me eyes of wisdom (20). We are men of perverse understanding, gifted with fleshy eyes. Therefore whatever we do without judging is not accomplished (21). However we have obtained thee now who art the God of gods. May my vision grow wise and works be accomplished (22). The wise, like great commanders, render fruitful unaccomplished works by the discernment of moral laws (23). Having obtained thy shelter, I do not entertain any fear. Listen to what I wish to accomplish now (24). O king of gods, I do not wish to allow my daughter to hold her Swayamvara lest she may choose
  • 52. another. Be thou propitiated with me, O Lord of celestials. Do not be angry with me" (25). Krishna said:—"O king of great intelligence, O sinless one, I do not perceive the utility of your sayings. Who can adjust whether you will give away your daughter or not (26). O king, the goddess-like form of Rukshmini has brought me to this place. But I should not say that you should give her to me and not to anybody else (27). When in the days of yore the gods assembled on the summit of the mount Sumeru for incarnating their portions they said to her: 'O thou of spacious hip, do thou with thy husband go to the world of men. And having been born in the house of Bhishmaka in the city of Kundina, be thou united with Keshava (28–29)'. I tell you this plainly, O king; do what ever you think proper after due consideration (30). O king, truly your daughter Rukshmini is not a woman; she is the very goddess Sree. For some object and at the words of Brahmā she is born (as a woman) (31). She should not be given away in a Swayamvara where all the kings will be assembled. She must remain alone, and inviting one bride groom, you should confer her on him. It will be thus performing a Kshatriya's duties (32). O king, you cannot give away Lakshmi in a Swayamvara. Selecting a good bridegroom, you should give her away according to proper religious rites (33). In order to put impediments in Swayamvara Vinata's son has been despatched by the king of gods and has come to the city of Kundina (34). I too have come here to witness this Swayamvara festivity of the kings and your daughter, the beautiful Kamala without lotuses (35). Your saying before me 'Forgive me' is considered by me as proper. And I do not find any folly in it, O king (36). O lord, I have already been pacified. Know me as conciliated
  • 53. since I have come to your territory in a gentle form (37). O king, to cast off one's shortcomings is forgiveness and it is endued with many virtues. So, how can the mind of one like myself be possessed by the sin of non-forgiveness (38). How can sin, O king, be attached to you who are moral, truthful and born in a family possessing the quality of goodness (39). Know me conciliated particularly as I have come with my army, for with them I never confront my enemies (40). When I cherish no forgiveness in my heart I go on the back of my carrier, Garuda, the foremost of birds, with weapons effulgent like the sun in my hand (41), O king, you are of the same age with my father and are therefore adorable unto me like him. Behaving with me, as a father treats his son, govern your kingdom well (42). How can that sin, which resides in the heart of a coward, find room in the heart of a pure-souled hero (43)? Know my conduct as pure as a father's feeling towards his son. Treating us with hospitality, these two kings of Vidarbha have given us their kingdom. By the fruit of this gift their ancestral manes of ten generations upwards have gone to the celestial region (44-45) And ten succeeding generations too of their royal line from son to grandson will also repair to the celestial region (46). And they two, enjoying their kingdom for many long years, without any thorns, will attain to emancipation when they will wish it (47). And those noble kings, who were present at my Abhisheka, will in time repair to the celestial region (40). O king, may you fare well! I shall now with Vinatā's son go to the charming city of Mathura protected by the king Bhoja" (49). Vaishampāyana said:—Saying this to the king Bhishmaka, welcoming all other kings and issuing out of the Hall with Kratha and
  • 54. Kaishika, the lords of Vidarbha, Krishna, the foremost of gods and Yadus, went to his car (50). Beholding the departure of Keshava, the faces of the royal saint Bhishmaka and of other kings were stricken with sorrow (51). At that time beholding the prime and self-sprung Krishna, having eyes like red lotuses, thousand feet, thousand eyes, thousand arms, thousand lustrous crowns, thousand heads, adorned with celestial garlands, raiments, scents, unguents and ornaments, holding uplifted celestial weapons and having three eyes of the sun, moon and fire, the king Bhishmaka bowed unto him and began to eulogise his glories, with his body, mind and speech (52–55). Bhishmaka said:—O God of gods, O Nārāyana, O Parāyana, thou hast no origin or destruction. Thou art the eternal prime Deity, I bow unto thee (56). Thou art the self-sprung Deity, art identical with the universe, lotus navelled, hast clotted hairs, dost hold a staff and art of coppery hue. I bow unto thee (57). Thou art Hansa, the discus, Vaikuntha, unborn and the great Atman. I bow unto thee (58). Thou art Yogin, the existent and non-existent, the ancient Purusha, the foremost of Purushas, above three-fold qualities. I bow unto thee (59). O Lord, O foremost of the celestials, that alone art the lord of all the worlds and the lord of those who have acquired a know fledge of the soul. I am thy votary. Be thou propitiated and confer on me a boon (60). Vaishampāyana said:—Having thus chanted the glories of the great God Krishna in the presence of the king, Bhishmaka made a present of precious gems, pearls, and plates of Vaidurja unto him. Thereupon he saluted in this way the highly powerful son of Vinatā too (61–62).
  • 55. Bhishmaka said:—I bow unto that celestial bird, the son of Kashya endued with the velocity of the wind who can assume various forms at will (63). Vaishampāyana said:—Having thus chanted, in brief, the glories of Vinatā's son Bhismaka offered him various sorts of most excellent raiment. After the lotus-eyed Krishna, the younger brother of Vāsava, on taking leave, had departed all the kings followed him. Having thus received honors, taken farewell of all the kings, placed Vinatā's son the foremost of birds, of a gentle form before him, been encircled by huge cars, and lighted up all the quarters the energetic Krishna set out for Mathurā. At that time there arose a great tumult consisting of the sound of bugles, trumpets, conches, the hissing of the serpents, the neighing of horses, and the rattle of the wheels of the cars resembling the muttering of huge clouds. After the departure of the highly powerful Krishna the gods repaired to the celestial region with that assembly hall and the most excellent seat. Encircled by their huge four-fold forces the kings followed Janārddana, a distance of two miles and afterwards at his command returned to Swayamvara (64–69).
  • 56. CHAPTER CIX. JARASANDHA'S PROPOSAL TO INVITE KALAYAVANA. Vaishampayana said:—After the departure of Vasudeva's son the kings, who had their limbs embellished with ornaments and who were anxious to go to their respective kingdoms, returned to the assembly-hall of Bhishmaka in order to inform (Jarāsandha of their intention) (1). Thereupon king Bhishmaka, the foremost of kings and well-read in moral laws, said to the kings, effulgent like the sun and the moon and seated at ease on beautiful seats (2). "O ye kings, you all know the calamity that will befall the Swayamvara. Do you forgive me for the fruit that is the outcome of my misconduct" (3). Vaishampāyana said:—Having thus addressed and welcomed duly all the kings, (the king) sent away all the monarchs of Central India and of the East, West and Northern Provinces. Having honored the king Bhishmaka duly in return, those kings, the foremost of men and mighty car-warriors, went away delightedly. Jarāsandha, Sunitha, the energetic Dantavakra, the king of Soubha, the king Mahākurma, Kaishika, all the leading kings of the Pravara race, the royal saint Venudāri, the king of Kashmira all those and other kings of the Deccan remained by Bhishmaka desirous of listening to the mystery. O monarch, beholding these kings waiting there the powerful king Bhishmaka, with an affectionate heart and grave and cool voice, said to them moral words relating to three-fold objects and embellished with figures.
  • 57. Bhishmaka said:—"O ye kings, I have acted thus in pursuance of moral words given vent to by you; you should forgive me for we must always abide by moral laws" (4-12). Vaishampāyana said:—Having thus expressed himself in the concourse of kings, the king Bhishmaka, well-versed in moral laws, again said aiming at his son (13). Bhishmaka said:—Observing the movements of my son my eyes are agitated with fear; I consider all now as mere boys. He (Krishna) alone is the foremost of Purushas (14). He, the very incarnation of glory, the foremost of the illustrious, the partaker of fame and powerful, has established great fame and the might of his arms in this land of mortals (15). Blessed is Devaki, the foremost of damsels who has conceived as her son the lotus-eyed Krishna, identical with the sum total of beauty, the greatest of all in the three worlds, and adored of all the immortals and who has seen his lotus countenance with her eyes full of affection (16-17.) Vaishampāyana said:—When the king Bhishmaka gave vent to these words again and again in the midst of the assembled kings the highly effulgent king Shalya said in sweet words (18). Shalya said:—O slayer of thy enemies, O lord of kings, do not lament for thy son. The Kshatriyas meet either with success or defeat in battle (19). This is the inevitable course and eternal religion of the mortals. Save Baladeva and Krishna what third person can withstand thy highly powerful son in battle? Taking up his bow thy mighty-armed son is alone capable of withstanding the car- warriors and great heroes of the enemy in battle. When by the might of his arms he handles the Bhārgava weapons, difficult of being used even by the celestials what man is capable of bearing it? This Eternal
  • 58. Purusha Krishna is without birth or death (20-23). In this land of mortals even the holder of trident (Siva) cannot defeat him. O Emperor, thy son is well-versed in the true meaning of all the Shastras (24). Knowing Keshava as Ishāna he did not engage in fight with him. It is not that there is none who can defeat him (25). Kālayavana is incapable of being slain by Keshava. With a view to have a son the great Muni Gārgya adored Rudra for twelve years living on powdered iron and practising dreadful and highly difficult penances. Thereat pleased when Shankara offered him a boon Gārgya prayed for a son whom the kings of Mathurā would not be able to slay. Rudra granted him the boon, saying 'so be it' (26-28). Thus by virtue of Rudra's boon, Gārgya's son Kālayavana is unslayable by the kings of Mathura in the battle-field and especially in the city of Mathurā (29). Though Krishna is highly powerful amongst the princes of Mathura still if he comes to battle and fights with him he will be able to defeat him (30). O kings, if you accept my words as becoming and sound, send an emissary to the capital of the king of Yavanas (33). Vaishampāyana said:—Hearing the words of the highly powerful Shalya the king of Soubha all the leading kings were delighted and said "We will do it" (32). Hearing their words and recollecting those of Brahmā the Emperor Jarāsandha lost heart and said (33). Jarasandha said:—Alas! formerly, assailed by the fear of a foreign king, all the Chiefs, seeking refuge with me, used to get back their lost kingdoms, servants, army and conveyances (34). Now, on account of their bad feelings towards their lord, they, like unto a damsel, coming in contact with a stranger, are now exciting me to seek another's shelter (35). Alas! even when I, afraid of Krishna, am
  • 59. constrained to seek refuge with another, Destiny alone is powerful. And by no means can any one overcome it (36). O ye kings, it is better for me to die than to seek helplessly the protection of another (king). I shall not therefore seek refuge with any body else (37). I shall give him battle who has been pointed out as my Death by the invisible words, may he be Krishna, or Baladeva, or a man, or some one amongst the immortals (38). Even this is my firm resolution and such is the conduct of a worthy person. I shall not act against it seeking another's protection (39). Even if you be all well disposed he (Krishna) may destroy you all. For your protection I shall send an envoy to him (40), O kings, the messenger should so proceed by the etherial way that Krishna may not put in any impediment. Do ye find out such a person who can go in this way (41). This effulgent king of Soubha is gifted with the prowess of fire, the sun and the moon. In a sunny car let him proceed to the capital of Yavana (42). Let him approach the king of Yavanas as our envoy and communicate to him our quarrel with Krishna. Let him try to bring him over to this assemblage of Chiefs (43). Vaishampāyana said:—Having thus expressed himself the Emperor Jarāsandha again said to the powerful king of Soubha: —"Do thou depart, O giver of honors and help all these Chiefs (44). Use such tactics that the king of Yavanas may proceed and vanquish Krishna and we may be pleased" (45). Having thus commanded all and worshipped Bhishmaka duly the Emperor, encircled by his own army, set out for his city (46). Shalya, too, the foremost of kings, having honored all duly, set out by the etherial way in a car, coursing like air (47). Following Jarāsandha to some distance the Deccan Chiefs repaired to their
  • 60. respective cities (48). Thinking of his own evil conduct, of Krathā, Kaishika and Krishna, the king Bhishmaka, along with his own son, entered into his Palace (49). On account of the discomfiture of the kings consequent upon Krishna's arrival and the termination of the Swayamvara the chaste and wise Rukshmini approached her friends and with her face bent down in shame said:—"I tell you truly, I do not wish to be the spouse of any body else save Krishna having lotus eyes" (50-51).
  • 61. CHAPTER CX. SHALYA MEETS KALAYAVANA. Vaishampayana said:—Kālayavana, the king of Yavanas, was highly powerful and used to govern the inhabitants of his city in pursuance of royal duties (1). He was wise, conversant with three Vargas,274 proficient in six Gunas275 innocent of sevenfold calamities,276 endued with all accomplishments, well-versed in Srutis, pious, truthful, a master of his senses, acquainted with the rules of war, an expert in capturing forts, heroic, of great strength and used to honor his ministers. One day encircled by his ministers he was seated at ease and the learned and intelligent Yavanas, discoursing amongst themselves on various celestial themes were adoring him (2–5). In the meantime there blew delightful, but exciting, cold and fragrant wind. Thereat the assembled Yavanas and the king Kālayavana were all worked up and thought "Whence it has come?" Thereupon they saw a car coming from the south. It was golden and white, lighted up with the lustre of jewels, adorned with celestial flags and pennons, drawn by horses fleet like the mind or air, adorned with tiger-skins, a terror to the enemies, the enhancer of joy to the friends, constructed by the celestial Architect, effulgent like the sun, the grinder of others' cars and embellished with jems like the rays of the sun and moon. The powerful and beautiful king of Soubha was seated thereon. Delighted greatly at seeing his friend the mighty- armed king of Yavanas, the foremost of speakers, repeatedly sent for Arghya and water to wash feet. And rising up from his throne and with Arghya in his hands he went out and waited at the landing
  • 62. stair of the car. Be holding the king Kālayavana, powerful like Sakra the highly energetic Shalya was greatly delighted, got down alone from the chariot with a confident heart and joyously entered into the Palace of Yavana for seeing his friend. Observing arghya in the hands of the king of Yavanas, Shalya, the foremost of kings, said in sweet words:—"O thou of great effulgence, I am not now worthy of arghya. I am now an envoy of the kings and have been despatched to thee by the intelligent Jarāsandha. I therefore do not deserve arghya from the kings" (5–18). Kalayavana said:—"O you of large-arms, I know that you have been despatched here as an envoy by the king of Magadha for the behoof of kings (19). O intelligent king, I adore you duly with water to wash feet, seat and various other means of welcome because you have been sent here by the entire circle of kings. By adoring you, O king, I shall worship the entire host of kings and by honoring you all of them will be honored. Therefore, O king, sit with me on this throne" (20–21). Vaishampāyana said:—Thereupon shaking hands with each other and enquiring of their mutual welfare those two kings sat at ease on the sacred throne (92). Kalayavana said:—What has become impossible to him, depending on the might of whose arms you kings are all living without any anxiety as the gods do under the protection of Sachi's lord, that he has sent you to me. Tell me, truly, O king, what mandate, the powerful king of Magadha has issued to me. Even if it be very difficult I shall carry out his command (23-24). Shalya said:—O king of Yavanas, hear I shall describe at length what the king of Magadha has deputed me to communicate to you
  • 63. (25). Jarasandha said:—The highly irrepressable Krishna has been oppressing the world from his very birth. Informed of his wicked deeds I attempted to slay him (26). Accompanied by a number of kings along with their four-fold forces and conveyances I besieged the mount Gomanta with a huge army (27). And there listening to the highly sensible words of the king of Chedi I set fire to that best of mountains for their (Rāma and Krishna's) destruction (28). Beholding that fire consisting of hundreds and thousands of flames and resembling the fire of dissolution, Rāma, holding the golden hilt of a sword, leaped down from the mountain summit in the midst of the ocean-like army of the kings. And that highly irrepressible one began to kill the car-warriors, the infantry and cavalry (30). He moved about like a serpent; and catching elephants, horses and soldiers with his plough-share he grinded them with his mace (31). In that battle-field abounding in hundreds of kings that highly energetic Rāma, endued with the prowess of the sun, ranging in various ways like the setting sun, destroyed elephants, with elephants, car-warriors with cars, and the cavalry with horses (32- 33). After Rāma, the highly powerful and energetic Yadu hero, Krishna, taking up his discus effulgent like the sun, and his black iron club, forcibly leaped down in the midst of the enemie's army agitating the mountain with the force of his feet as a lion attacks the poor deer (34–35). O king, at that time whirling and bathed with shower that mountain extinguished the fire and entered into the earth as if dancing (36). Jumping down from that burning mountain Janārddana with his hand holding the discus began to destroy our army (37). Whirling his huge discus and throwing all down with his
  • 64. club he began to grind men, elephants and horses with his mace (38). Then with the fire of discus and plough-share begotten by their anger that huge army, protected by sun-like kings, was consumed (39). Within a moment our army consisting of men, elephants horses infantry and flags, was consumed by those two foot soldiers (40). O king, beholding that army distressed by the fear of the fire of discus and routed, I, encircled by a huge collection of cars, engaged in battle. And Keshava's brother the heroic and valiant Baladeva, the destroyer of Bala, stood before me with a club in his hand (41–42). Having slain the twelve Akshouhinis of soldiers and cast off his plough-share and mace Sounanda, that leonine hero pursued me with his club (43). O king, having thrown the club on me with a force like that of the fall of a thunder-bolt he again stood manfully on the ground (44). Then like unto Kārtikeya at the time of the destruction of Krounch, he, with his two large eyes, as if consumed me, looking at my joints (45). O king of Yavanas, beholding such a form of Baladeva, what person, having hopes of life, can stand before him in the battle-field (46)? When he stood before him holding up that terrible club resembling the rod of the Regent of the dead and whirling it along with his plough-share Brahmā, the grand- father of all, filling the welkin with his invisible voice grave as the muttering of clouds, said:—"O sinless Rāma, do not strike (him); O holder of plough-share, it has been destined that he shall not meet with his death from any other person." Hearing with my own ears those words given vent to by the Grand-father I was filled with anxiety and returned from the battle-field (47–50). O king, for this reason, and for the behoof of the kings, I communicated this incident to you. Hearing this you should do what
  • 65. you think proper in pursuance of my words (51). Desirous of having a son your father propitiated Sankara, the god of gods with hard austerities and obtained you as his son unslayable by the princes of Mathurā (52). Fasting and feeding on powdered iron for twelve years the great Muni Gārgya propitiated the great god Siva, on whose lotus feet even the gods and Asuras meditate and therefore obtained his wished-for prosperity in the person of yourself (53). By virtue of the asceticism of the ascetic Gārgya and of the power of Mahādeva carrying the emblem of a crescent forsooth, shall Janārddana meet with his death as the dews are dried up by the rays of the sun (54), O king, thus requested by the kings, be up and doing and march for vanquishing Krishna. And entering the city of Mathurā with your army establish your glory there (55). Vasudeva's son is a native of Mathurā and Baladeva is his brother. If you go to the city of Mathurā you will be able to defeat them in battle (56). Shalya said:—O king, I have thus communicated to you, the message entrusted to me by the Emperor Jarāsandha for the behoof of the kings. Do you now undertake what is proper and conducive to your well-being after consulting duly with your ministers (57). [274] Three conditions of a king or state; prosperity, evenness or decay or loss, gain and equality. [275] The six acts of a king in his military character, or peace, war, marching, halting, sowing, dissension, seeking potection.
  • 66. [276] The seven calamities are gambling, sleeping in a day, calumny, whoring, playing, idle roaming, drinking and hunting.
  • 67. CHAPTER CXI. KALAYAVANA AGREES TO KILL KRISHNA. Vaishampayana said:—After the king Shalya, as directed by the Emperor Jarāsandha had said this Kālayavana, the king of Yavanas, with great delight said (1). Kalayavana said:—Oh! highly honored and blessed I am; and my life is crowned with success since numberless kings have requested me for vanquishing Krishna (2). The kings have appointed me in the work of subduing Krishna who is invincible in the three worlds, even unto gods and Asuras. And they have blessed me so that I will achieve victory (3). While the kings, with delighted hearts, have declared my victory I shall, by the very pouring of their water-like words, achieve success (4). Whatever it may be, I shall carry out the command of the Emperor Jarasandha issued at the request of the kings. Even my discomfiture in it will be, tantamount to my success (5). O king, to-day, the day and the stars are auspicious and in this auspicious moment I shall even to-day start for Mathurā for defeating Keshava in the battle-field (6). Vaishampāyana said:—Having thus addressed the powerful Shalya the king of Soubha, the lord of Yavanas honored him duly with highly precious jems and dresses (7). Afterwards for acquiring unstinted blessings he gave away various riches to his guest and the Brāhmanas and duly offered libations to fire. Then after the performance of benedictory rites he set out with his army for vanquishing Janārddana (8–9). O foremost of Bharatas, king Shālya
  • 68. too, with his desire fully achieved, embraced the lord of Yavanas and set out with a delighted heart for his own city (10).
  • 69. CHAPTER CXII. UGRASENA RECEIVES KRISHNA. Janamejaya said:—O Brahman, when the Lord Krishna, endued with Sakra's prowess, set out from the city of Bidarbha he did not ride the highly powerful son of Vinatā, Garuda; why did he then take him away with him? And what did Vinatā's son do? O great Muni, I am filled with great curiosity in this; do thou unfold the mystery (1–2). Vaishampāyana said:—O king, listen to the work, difficult of being done by men, which the highly effulgent son of Vinatā performed after his departure from the city of Bidarbha (3). O lord, before his departure to the city of Mathurā when Janārddana, the god of gods, said before the assembled kings, "I shall repair to the charming city of Mathura governed by the Bhoja king" the beautiful and intelligent son of Vinatā thought for a considerable time, and then saluting Vāsudeva, after he has finished his say, said with folded hands (4–6). Garuda said:—"O god, I shall now proceed to Raivata's city Kushasthali, to the charming mount Raivata and the adjacent forest thereto resembling the garden of Nandana (7). "The Rākshasas have abandoned the charming city of Kushasthali. It is situate at the base of the Raivata mountain and on the bank of the great ocean. It abounds in trees decorated with filaments of flowers, in groves and creepers. It is scattered with elephants and serpents, and inhabited by bear, monkeys, boars, buffaloes and deer. I shall perfectly examine (that place) and see if it
  • 70. is worthy of thy habitation. O lord, if that extensive and charming city is fitted for thy residence, I shall remove all the thorns and come back to thee" (8-10). Vaishampāyana said:—Having thus expressed himself before Janārddana, the king of gods, and saluted him the powerful lord of birds set out towards the western direction (11). And when Krishna too, with the Yadavas, entered into the beautiful city of Mathurā, Ugrasena came out of the city with dancing girls and citizens and honored the victorious Krishna (12). Janamejaya said:—What did the mighty-armed Emperor Ugrasena do when he heard of Krishna's installation by the numberless kings (13)? Vaishampāyana said:—Hearing of Krishna’s installation as the Emperor by numberless kings, of Indra's making peace with him through his envoy Chitrangada, of the apportionment of wealth, each king being entitled to a lakh, each emperor to a Arvuda and each ordinary men to ten, and that every one, who came there, did not go away empty handed and that the graceful lord of Nidhis, Sanka, commanded by the gods, distributed wealth after Krishna's heart, from his own men and other persons informed of people's conduct, Ugrasena offered a great puja at the temples of the tutelary deities. The two sides of the gate of Vasudeva's house were decorated with flags, pennons and garlands. He also decorated with flags Kansa’s assembly hall Suprabhā adorned with various sheets of cloth (14-20). The doors of the sitting-room of the Emperor Krishna in Gopura were pasted with ambrosia by the king (21). There was dancing and music on all sides. The city was decorated with flags, garlands of wild flowers and jars full of water (22). The king
  • 71. sprinkled sandal water in all the high-ways and spread sheets of cloth on the ground (23). On both sides of the roads incense was kept in vessels and continually burnt with Aguru, molass and various other articles (24). The elderly women began to sing benedictory hymns and youthful damsels moved about anxiously in their respective houses (25). Having thus commenced the festivity in the city the Emperor Ugrasena repaired to Ugrasena's Palace and after communicating to him the pleasant news and consulting with Rāma went to the car. O king, in the meantime the great sound of the conch-shell Pānchajanya was heard. Hearing that sound of the conch the entire city of Mathurā, with their women, boys, elderly men, panegyrists, songsters, and accompanied by a huge army, issued out placing Rāma before them. Ugrasena himself carried arghya and water for washing feet for Krishna (26–29). After going over to some distance and coming within the view of Vāsudeva the Emperor Ugrasena desired to proceed on foot and accordingly got down from his white car (30). And beholding Hari, the king of gods, seated on a charming car adorned with celestial jewels he, in words suppressed with joy, said to the lotus-eyed Rāma the slayer of his enemy's army. Krishna was adorned with ornaments set with jewels, was shining like the sun on account of the garland of wild flowers decorating his breast, was accompanied by fans, umbrellas and flags with the emblems of Garuda painted thereon, embellished with all the marks of royalty and endued with the beauty of the rising sun (31–34). (Ugrasena said):—"O great one, it does not behove me to proceed on car after this. Thinking this I have got down. Do thou go
  • 72. on the car (35). Coming to Mathurā in the disguise of Keshava Vishnu has manifested himself as the king of gods in the ocean-like assemblage of the kings. I therefore wish to chant his glories properly." The highly effulgent elder brother of Krishna (then) replied to the king (saying) (36–37): "O king, it is not proper to chant the glories of that best of kings at the time of his going. Without it Janārddana is pleased with you. What is the use of hymning him who is himself propitiated? Your visit is identical with your chanting of his glories. While Krishna, although he has acquired the dignity of the Lord Paramount, is coming to your house, what is the use of praising him with celestial and super-human hymns?" Thus conversing with each other they went to Keshava (38–40). Beholding the king Ugrasena approach with arghya in his hands Krishna, the foremost of orators, stopped his car and said:—"O king of Mathurā, while I have installed you, declaring, 'Be you the lord of Mathura' it does not behove me to make it otherwise. O king, you should not offer me arghya and water for washing my feet and rinsing my mouth. This is my heart-felt desire (41-43). O king, informed of your intention I say that you are the king of Mathura. Do not make it otherwise. O king, I will confer upon you your proper share in the land and gift. As I did with the other kings I had kept your share in reserve beforehand, one hundred thousandth portion without any ornaments or raiment. O king, get upon your white car adorned with gold, umbrella, fans, flags and celestial ornaments. And wearing your crown of sunny lustre govern the city of Mathurā, delightedly with your sons and grand-sons, defeat your enemies and multiply the Bhoja race. The king of gods, the holder of thunder-bolt
  • 73. sent, for Ananta and Shouri, celestial ornaments and raiments. From the thousand jars of gold coins reserved for the citizens of Mathurā in that ceremony of installation the king of gods has ordered that one thousand should be given to each of the panegyrists and bards, one hundred to each old man, prostitute and other men and ten thousand to each of the Yādavas, Vikadru and others who live with the king Ugrasena (44–52)". Vaishampāyana said:—Having thus honored the Emperor Ugrasena in the presence of all the soldiers Janārddana, with great delight, entered the city of Mathurā (53). On account of the celestial ornaments, garlands, raiments and unguents it appeared as if he was living in the city of the celestials encircled by gods (54). Like unto the muttering of clouds there arose a great tumult consisting of the sound of bugles and trumpets, blare of conches, the noise of elephants, the neighing of horses, the leonine shouts of the heroes and rattle of car-wheels (55-56). The panegyrists began to sing his praises and the subjects to salute him with numberless presents. At this Hari was not the least surprised (57). He was high-minded by nature, shorn of egoism and has seen a greater display than this beforehand. And for this he was not filled with surprise (58). Beholding Mādhava's arrival who was shining in the lustre of his own person effulgent like the sun the inhabitants of Mathurā saluted him at every step and said (59): "He is Nārāyāna, the abode of Shree living in the ocean of milk. Leaving his serpent-couch he has come to the city of Mathurā (60). Having chained Bali irrepressible unto the immortals he conferred the soverignty of the three worlds on Vasava the wielder of thunder- bolt (61). Having slain Kansa, the foremost of the powerful and
  • 74. other Daityas this slayer of Keshi has conferred the kingdom of Mathura on the Bhoja king (62). Not being himself installed and not sitting on the royal throne, he, having acquired the dignity of the Lord Paramount, has entrusted Ugrasena with the government of Mathurā" (63). Having heard this conversation of the citizens, the bards, panegyrists and the poets sang, "O thou the ocean of accomplishments, how can we, who are one tongued men, sing the deeds begotten of thy prowess and energy (64–65). The thousand- headed serpent-king Vāsuki, who has the intellect of a god, can, with his two thousand tongues, to a certain extent describe thy accomplishments (66). It is a great wonder to the kings of the earth that a throne was sent by Indra. It never happened before nor will it be in future (67). The descension of the assembly-hall and jars from the celestial region has never been heard of or seen. Therefore we consider it as a wonder (68). O Keshava, conceiving a son like thee, the foremost of gods, Devaki, the best of damsels, has been blessed because she, with her eyes full of affection, saw thy lotus face adored by men and the immortals (69–70)". Placing Ugrasena before them and listening to the conversation regarding their praises sung by the citizens the two brothers Rāma and Krishna arrived at the gate and the king worshipped them repeatedly sending for arghya and water for washing feet and rinsing mouth (71–72). Thereupon approaching Keshava's car, saluting him with his head down and mounting on an elephant the energetic and intelligent Ugrasena began to shower gold as the clouds discharge their watery contents (73). Having thus showered gold on him the beautiful Mādhava arrived at his father's house and
  • 75. said to Ugrasena, the king of Mathura (74): "O lord, although I have secured the dignity of the Lord Paramount, this throne, conferred by the king of gods, should be kept in the king's Palace (75). Although acquired by the strength of my own arms I do not like to come by the assembly-hall of the king of Mathurā. O lord, I propitiate you. Do not be offended" (76). O king Janamejaya, at that time Vasudeva, Devaki and Rohini were so much overwhelmed with joy that they could not give vent to any word (77). O king, thereupon considering the importance of time and place, Kansa's mother, taking riches and presents of various countries acquired by him, went to Keshava and dedicated them to his feet. Observing it Krishna sent for Ugrasena and said in sweet words (78–79). Krishna said:—"It is time that has snatched away your two sons; I have not slain them either for riches or for the kingdom of Mathurā (80), O king of Mathura, having vanquished your enemies by the might of my arms do you perform many sacrifices and make profuse presents (81). O king, do you cast off your mental agony and fear consequent upon Kansa's death. I return you these riches; do you accept them" (82) Having thus consoled the king, Krishna, along with Balarama, went to his parents (83). There those two highly powerful heroes, with heart full of joy, saluted their parents bending their heads (84). O Janamejaya, at that time the city of Mathurā left off her own form and as if the capital of gods came down there leaving the celestial region (85). Beholding Vasudeva's house the citizens did not consider it as earth but took it for the region of the celestials (86).
  • 76. Having thus entered Vasudeva's house the heroic Baladeva and Keshava dismissed Ugrasena, the king of Mathurā and his queen. And then leaving off their arms and moving about for some time they went through the evening rites. And then seated at ease they conversed with one another (87-88). In the meantime there took place a highly dreadful calamity. The clouds were scattered in the sky, the earth and the mountains were shaken, the oceans were agitated, the serpents were terrified and the Yadavas, trembling, fell down on earth (89–90). Beholding them thus fallen the immoveable Rāma and Krishna, perceived, from the flapping of the huge wings, the approach of Garuda, the foremost of birds. And within a short time they saw Garuda by them. Saluting them both with his head, Vinatā's son, of a gentle form, adorned with celestial garlands and unguents, sat on a seat (61–92). Observing the arrival of his war-like minister, the intelligent son of Vinatā, the slayer of Madhu said: "O thou the grinder of the enemies of the celestial army, O delight of Vinatā's heart, O foremost of birds, O favourite of Keshava, may thy arrival here prove auspicious" (93–94). Having thus addressed Vinatā's son, stationed there like a very god Krishna again said to him who was equally powerful (95). Krishna said:—O foremost of birds, let us now go to the highly extensive inner appartment of the Bhoja king, for there, seated at ease we shall be able to hold counsels after our own hearts (96). Vaishampāyana said:—When having entered the inner appartment of the Bhoja king along with Vinatā's son, the highly powerful Krishna and Baladeva held parley, the former said:—"O Vinatā's son, the king Jarāsandha is unslayable by us. It has been so ordained. Incomparable is his might and he is encircled by a huge
  • 77. army and highly powerful kings. The army of the Magadha king consists of many soldiers and so we shall not be able to consume it even within hundred years. Therefore I tell you, O king of birds, that it never bodes good for us to live in this city of Mathura. Even it is my desire (97-100)". Garuda said:—O god of gods, having saluted thee I took leave and went to Kusathali for finding out a worthy habitation for thee (101), O foremost of gods, having gone there and been stationed in the welkin I reconnoitered all over that city endued with all auspicious marks (102). That city is situate in an extensive watery province of the ocean. It has the ocean on the east and is therefore always cool. It is surrounded on all sides by the ocean, a mine of every sort of jem, spread with trees conferring wished-for objects, covered on all sides with flowers of all seasons and therefore highly charming; it is the abode of all forms of Ashramas, satisfies every sort of desire, is filled with men and women, is always full of merriment, is encircled by ditches and walls, is embellished with palaces and gates, variegated courtyards and roads, has huge doors and gates, and various bolts and other contrivances, is adorned with a golden wall, is filled with car-warriors, cavalry and infantry, and with trees of various countries covered with celestial flowers and fruits, is adorned with flags and pennons, contains big palaces, strikes terror to the enemies, enhances the joy of the friends and is isolated from other cities presided over by kings (103-109). O god, there is that best of mountains Raivata resembling the garden of Nandana. Do thou make it an ornament of thy gate (110). O foremost of gods, that city will also be liked by thy sons. Do thou go and live there (111). Like unto Indra's capital Amarāvati thy city will
  • 78. 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