Frances Buontempo Foreword by Kevlin Henney The Easy Way to Start Learning Modern C++ Introducing C++
9 7 8 1 0 9 8 1 7 8 1 4 7 5 5 9 9 9 ISBN: 978-1-098-17814-7 US $59.99 CAN $74.99 PROGR AMMING / C++ You know how to code, but you’re ready to level up. You’ve heard about the power and performance of C++, a language vital to fields like AI, game development, and high-performance computing. But where do you even start? Existing resources are outdated or overly academic, or they assume a deep understanding of C. You need a guide that respects your existing skills and gets you coding fast with modern C++. This book cuts through the noise, focusing on the essential elements of C++ with hands-on projects that quickly build your skills and confidence. Author and C++ expert Frances Buontempo gets you up to speed quickly with the latest features and best practices of the language, preparing you for more advanced exploration. • Write clean and efficient C++ code • Understand core concepts and syntax • Apply various programming approaches, from OOP to functional styles • Read and understand complex C++ definitions and resources Frances Buontempo is the editor of ACCU’s magazine, Overload, and has been a professional programmer since the 1990s. She holds a PhD in data mining and writes and speaks about C++ and machine learning. She mentors developers, promotes unit testing, and makes complex topics easy to understand. Introducing C++ “Finally, a C++ book that saves the sharp edges for later and lets you build real things first. Modern, practical, and long overdue.” Matt Godbolt, Compiler Explorer “It’s wonderful to see a fresh book that not only uses C++ to teach programming from scratch but that starts with modern C++23! With the number of C++ programmers worldwide growing every year with no sign of slowing down, this book is very timely.” Herb Sutter, ISO C++ committee chair
Praise for Introducing C++ It’s wonderful to see a fresh book that not only uses C++ to teach programming from scratch but that starts with modern C++23! With the number of C++ programmers worldwide growing every year with no sign of slowing down, this book is very timely. —Herb Sutter, ISO C++ committee chair This is the book I wish I’d had under my pillow when I started with C++ many years ago after coming from a long career using other programming languages. —Daniela Engert, senior software engineer at GMH Prüftechnik GmbH and member of the C++ standardization committee Finally, a C++ book that saves the sharp edges for later and lets you build real things first. Modern, practical, and long overdue. —Matt Godbolt, Compiler Explorer I’ve been out of the C++ sphere for some time, but Buontempo’s text is clear and the explanations are excellent. The chapter on Lambdas was particularly helpful for me as a total newbie--I didn’t understand all the fuss about Lambdas until I read it. —Emyr Williams, ACM member
(This page has no text content)
Frances Buontempo Foreword by Kevlin Henney Introducing C++ The Easy Way to Start Learning Modern C++
978-1-098-17814-7 [LSI] Introducing C++ by Frances Buontempo Copyright © 2026 Frances Buontempo. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 141 Stony Circle, Suite 195, Santa Rosa, CA 95401. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Brian Guerin Development Editor: Sarah Grey Production Editor: Ashley Stussy Copyeditor: Emily Wydeven Proofreader: Kim Wimpsett Indexer: nSight, Inc. Cover Designer: Susan Brown Cover Illustrator: José Marzan Jr. Interior Designer: David Futato Interior Illustrator: Kate Dullea March 2026: First Edition Revision History for the First Edition 2026-03-10: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098178147 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Introducing C++, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
To the memory of our cat Vim
(This page has no text content)
Table of Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1. Hello, World!. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Installing Tools 3 Linux and macOS 3 Windows 4 Using Your Tools 4 Running Your Program 7 Writing to the Screen 7 Using println 8 Troubleshooting 10 Using cout 11 Understanding println and cout in Depth 12 Conclusion 14 2. Variables and Keyboard Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Declaring Variables 15 Character Input 16 Detecting Input Problems 18 Input of Real Numbers 18 Detecting Problems with Numbers 19 Detecting More General Problems 22 A Function for Input with Some Tests 24 Starting with a Failing Test 24 Breaking Your Code into Functions 26 Starting with a Failing Test, Again 27 vii
Testing Bad Input 29 Refactor 31 Calling Your New Function from main 32 Understanding Variables, std::cin, and Functions in Depth 33 Clearing Input Errors 34 More on Functions 37 Conclusion 41 3. Exceptions and Expectations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Exceptions 43 Throwing Exceptions 46 Trying and Catching 47 Handling Exceptions with a try/catch Block 47 Expectations 49 Understanding Exceptions and Expectations in More Depth 51 Other Exception Types 52 Position of catch Blocks 54 Expected Without a Value 55 Conclusion 56 4. Using Loops, Arrays, and Vectors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Input of Several Numbers Using a Loop 59 A while Loop 60 Using an Array 62 Displaying and Using the Numbers 68 Using a Vector 71 Adding More Elements to a Vector 72 A Few Other Container Functions 74 Getting Several Numbers in a Vector 75 Understanding Sequential Containers in More Depth 76 Initializing Containers with an Initializer List 76 What Happens When You Add to a Vector 77 What Happens When You Delete from a Vector 78 Initializing a Vector with a Fixed Value 79 Other Sequential Containers 80 Conclusion 80 5. Using Standard Library Algorithms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Getting Several Numbers Into a Vector (Again) 83 Analyzing Your Numbers Using Algorithms 89 Using Predicates in Algorithms 91 Using Iterators in Algorithms 94 viii | Table of Contents
The Old Way to Remove Items 95 Finding an Average with an Algorithm 99 Understanding Algorithms in More Depth 103 Using for Loops 103 Binary Operators and Predicates 106 More on Iterators 107 Conclusion 107 6. Lambdas and the Ranges Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Removing Negative Numbers Using a Lambda 109 Using a Lambda to Vary Behavior via std::function 111 Filtering Out Negative Numbers Using the Ranges’ View 117 Using Lambda Captures for Fun and Profit 120 Understanding Lambdas and Views in More Depth 123 Lambda Captures by Value 123 Lambda Captures by Reference 127 Composing Views 128 Lazy Views 132 Conclusion 133 7. Random Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Generating Random Numbers 136 Writing an Overload for a Function 139 Building a Trading Game 143 Understanding Code with Random Numbers (and Vectors) in Depth 146 Using a Normal Distribution 147 Considerations for Code That Uses Random Numbers 150 Creating and Filling Vectors 154 Conclusion 156 8. Working with Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Writing to a File 159 Detecting and Reporting Problems 161 Using the Filesystem Library 163 Reading from a File 165 Understanding Files in Depth 167 Different File Modes 167 Bitwise Operators and Bitmasks 169 Reading Previous Prices 171 Conclusion 175 Table of Contents | ix
9. Strings and Formatting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 C-Style String Literals and Characters 177 Providing Arguments to main 179 Creating and Manipulating a std::string 180 Other Ways to Create a std::string 181 More std::string Functions 182 String Views 184 Formatting and More on std::println 187 std::format and Format Specifications 188 An Improved Trading Game 190 Understanding Strings in Depth 195 Joining std::strings Efficiently 195 Using std::println to Save to a File 196 Conclusion 198 10. Classes: Member Variables and Member Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 A Simple Class 202 Private and Public Access Specifiers 205 Constructors and Destructors 208 Using the Stock Class in a std::vector 211 Introducing Classes in Depth 214 Constructors and Destructors in Depth 215 Splitting a Class Between Header and Source Files 217 Conclusion 219 11. Classes: Special Member Functions and Move Semantics. . . . . . . . . . . . . . . . . . . . . . . . 221 Copying Objects 221 Moving Objects 223 Move and Copy Assignments 225 Copies and Moves in Depth 229 How Does a std::string Work? 229 Move Constructors and Move Assignments 231 Copy Constructors and Copy Assignments 232 Conclusion 233 12. Memory Management with std::unique_ptr. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Creating a std::unique_ptr 236 Using a std::unique_ptr 238 Smart Pointers in Depth 239 More on Pointers and References 239 Unique Pointers in More Detail 241 Other Smart Pointers 243 x | Table of Contents
Custom Deleters 244 Using a std::unique_ptr in a Class 245 Using the Exchange Class 249 Conclusion 252 13. Classes: Virtual Functions and Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Base Class and Derived Classes 254 Defining an Abstract Base Class 254 A Derived Class 255 Using Derived Classes 258 A New Trading Game 261 Adding Another Derived Type 264 Virtual Functions and Inheritance in Depth 271 Virtual Destructors 271 Virtual Functions and Slicing 273 Conclusion 275 14. Using std::variant and std::visit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Creating and Using a std::variant 278 Using a std::variant in std::visit 281 Using the Event in the Trading Game 284 The std::variant in Depth 287 Spotting and Handling Potential Problems with std::variant 288 Using std::optional and std::any 289 Conclusion 291 15. Templates and std::unordered_map. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Making a Lookup Table 293 Write Your Own Template 295 Specializing std::hash 299 Adding an Equality Operator for an Event 302 Adding a Way to Display the Events 304 Keeping a Tally of Events in Your Trading Game 306 Associative Containers and Templates in Depth 309 More on Templates 311 Conclusion 314 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Table of Contents | xi
(This page has no text content)
Foreword C++ is a big language, but it is not well served by a big book. This is especially true for an introduction to the language. An introduction is a beginning, not an every‐ thing. You want preparation, not intimidation. You want an on-ramp, not the north face of the Eiger. The first steps should encourage you to take the next steps rather than scare you off the path. And that’s the beginning Fran has given you. This introduction is complete, but not in the sense that it braindumps everything a C++ expert of many decades standing might know. It equips you with the skills to write real code, the freedom to choose where you want to go next, and the confidence to follow through. This book may be the beginning of your C++ journey, but it’s also a journey in its own right, one that starts in the foothills of “Hello, world!” and travels into the world of stock prices and asset trading. But make no mistake, this is not some passive tourist experience where you cruise past the sights of the language and its library from the window of a tour bus. This is a walking route that takes in landmarks and alleyways, paved streets and potholes, working code and compilation errors. You’ll get a feel for the place and what it’s like to live and work there. Fran is your guide. She knows the sights, the sites, and how to steer you clear of any trouble. This is a book of doing. Sit with the book open, crouched—or upright, the posture is yours to choose—over a keyboard. You’ve got an editor brimming with brace-laden code, a console flowing with commands and messages, and inputs and outputs, all surrounded by a flotilla of open browser tabs. Every page of this book is bursting with an invitation to do something—something to try for yourself, play with, puzzle over, be delighted by, and build on. Fran offers careful and deliberate guidance, filling in the gaps other guides either skip over or get lost in. She presents a simpler path, while ensuring your progress is real. She does not oversimplify or pull any punches—and C++ can summon quite the punch. When you’re coding in the zone and your code is working, the going’s great; xiii
when things are off, however, C++ can be unforgiving. Fran offers the understanding and support you need. Good habits—from design to testing—line your route through the language. Con‐ structs and concepts are introduced on an as-needed basis rather than thrown at you in bulk. You will learn and employ language mechanisms, library features, and tech‐ niques many experienced C++ developers might consider advanced or be unaware of. The practical flow of this book, however, means they feel appropriate and in service of the problem being solved. No fanfare, no scaremongering, no infodumps, just the right tool for the job. OK, are you ready? Let’s take those first steps! — Kevlin Henney author of Pattern-Oriented Software Architecture and editor of 97 Things Every Programmer Should Know xiv | Foreword
Preface You already know how to code, perhaps just a little, but haven’t tried C++ yet. You’ve come to the right place. C++ is an old language, which has evolved over time. C++ has a reputation of being a difficult language to learn, but I will explain the basics to you. You’ll get a deeper understanding of what is happening under the hood in other languages when you take time to learn C++. If you learn C++, you will therefore find many other lan‐ guages easier to learn. It’s worth putting in the time and effort. There hasn’t been a new introductory book recently, so the time had come to write one. There are many older, excellent books, but they don’t cover newer language standards. One of my favorites is Accelerated C++: Practical Programming by Example by Andrew Koenig and Barbara E. Moo. This is still an excellent resource but doesn’t cover newer features, since it was published in 2000. I’ll show you newer C++ features, building up a small program over the course of the book. I mostly target C++23 but give you a glimpse of a few C++26 features too. I also cover older features that haven’t changed. I don’t have space to cover everything, but you don’t need to know everything to get the basics of the language. I’ll cover enough to give you a solid foundation. Who Is This Book For? I have written this book for people who don’t know C++ but have maybe program‐ med a little in another language. Whether you are a student or a seasoned pro, you will gain something from learning C++. If you have done a little C++ a while ago, this book will help you get back up to speed. I don’t assume any existing knowledge, and I introduce the basics, including variables and loops, near the beginning. You will quickly learn how to use standard C++ fea‐ tures, including containers, to store values, and algorithms to find and sort those values. xv
You will also learn about classes, which you may have encountered in another lan‐ guage. If you haven’t, that’s fine. I will explain what they are for and how to use them in C++. Learning a more functional style, using algorithms, and an object-oriented style, using classes, will give you two different paradigms and more. C++ is very flexible, supporting various approaches, while allowing you to write efficient code. The knowledge you obtain is applicable to other programming languages, so is timeless. You might even want to pursue C++ afterward. My career was in a mixture of lan‐ guages but predominately C++ in finance, after starting with embedded machines like barcode scanners. I know many others who use C++ in games programming. There are careers out there waiting for you, if you’re interested. Or, you can simply learn C++ for the fun of it. Structure of This Book There are 15 chapters, starting with a "Hello, world!" program. This gets you started. You need to take a moment to set up your tools to write and build your code. By the end of the first chapter, you will know two different ways to write output to the screen. C++ frequently offers more than one approach, partly because as the language evolves, so do the features. It’s worth knowing more than one way to achieve your goals. From Chapter 2, you will start to build a program you will add to over the course of the book. You will learn how to get input in the second chapter, storing that input in a variable. This introduces the general idea of streams in C++, which you will revisit in Chapter 8 to load data from files. Many industrial-scale programs do not take input directly from a prompt. You would get input from another process, a database or via a graphical user interface (GUI). However, as a beginner it is useful to be able to pro‐ vide input to your program without having to set up a database or learn another new skill like GUI programming. I also show you how to do some basic testing. I show you how to deal with problems in Chapter 3. This chapter demonstrates exceptions and the newer std::expected. Several people were surprised by these making an appearance so early but decided it was a good idea after reviewing the book. Having thought about testing in Chapter 2, learning how to handle problems in this chapter will help you write good code, taking you beyond knowing the syntax. Chapters 4, 5, and 6 show you how to use the standard library, starting with arrays and vectors to store elements and moving on to loops, algorithms, and ranges. I also show you lambdas: a way to write a short function directly where you use it. You will start building a trading game in a program that you will add to over the course of the book. xvi | Preface
Chapter 7 shows you how to work with random numbers in C++. Knowing how to generate a random number means you can write a variety of games. This chapter will generate random prices, which you will use in the program you have been building. Chapter 8 shows you how to load prices for your trading game from a file. By this point, you have actually done the hard work, since files are another type of stream, so the code is similar to the second chapter, where you got input from the keyboard. Chapter 9 does a deep dive into strings; think words or messages. Strings come in various forms in C++, and I show you how to use C-style strings so you can send parameters to your main function. People used to claim you needed to learn the C programming language before you could learn C++. This is not true, though C++ did evolve from C and does use some C concepts and types. I will also show you more about using C++ strings, and you will see how much easier they are to work with. Chapters 10, 11, 12, and 13 show you how to write and use classes. C++ is sometimes described as an object-oriented (OO) language, meaning you write code based on a class: a way to group together variables and functions. You can write OO code in C++, but you don’t have to. These chapters require more details about how the lan‐ guage works and how to think about your design. Chapter 14 shows how to use a variant: a type that can be used for one of a fixed set of types. This newer feature can be used in various ways. I’ll also show you how to use the std::visit function to work with the various types in a std::variant. Together these form a newer approach to writing C++, and I believe they are a vital new feature. The book finishes with a look at templates and lookup tables, in the form of a std::unordered_map. Templates are a big topic and are very powerful. I only have space to give a short introduction, but it is enough to help you understand what you need to do to write your own template. By this point you will have covered a lot of C++, but not everything. You will have enough knowledge to continue your journey if you so wish. There will be more to learn, and C++ will continue to evolve. Knowing the basics will give you a solid grounding. Try to write the code as you read. Play with the trading game you produce, and note any questions you have as you read. Find someone to talk to if you get stuck. Find someone to share with if you understand something new. Above all, learn lots and have fun. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Preface | xvii
Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/doctorlove/IntroducingCpp.git. If you have a technical question or a problem using the code examples, please send email to support@oreilly.com. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Introducing C++ by Frances Buontempo (O’Reilly). Copyright 2026 Frances Buontempo, 978-1-098-17814-7.” xviii | Preface
Comments 0
Loading comments...
Reply to Comment
Edit Comment