|
From C++ Bookcamp by Frances Buontempo This article covers
|
C++ is an old but evolving language. You can use it for almost anything and will find it in many places. In fact, C++’s inventor Bjarne Stroustrup described it as the invisible foundation of everything. Sometimes it might be deep inside a library for another language because C++ can be used for performance-critical paths. It can run in small, embedded systems or it can power video games. Your browser might be using the language. C++ is almost everywhere.
The language is compiled and targeted at a specific architecture such as a PC, a mainframe, an embedded device, bespoke hardware, or anything else you can think of. If you need your code to run on various different types of machines, you need to recompile it. This has pros and cons. Different configurations give you more to maintain, but compiling to a specific architecture gets you “down to the metal”, allowing the speed advantage. Whatever platform you target, you will need a compiler. You also need an editor or integrated development environment (IDE) to write code in C++.
C++ stems from C, which has similar advantages but is a lower-level language. If you recognize ++ as the increment operator, you’ll realize the language’s very name suggests it is a successor to C. You can avoid the depths of pointers and memory allocations with C++, writing higher-level code. You equally can drop down to C or even assembler in C++ code. C++ never intended to take over the world or even replace C. It does provide many new ways to approach coding though. For example, you can do a surprising number of things at compile time, using type-safe features rather than preprocessor macros often used in C.
The language underpins diverse technologies, including compilers or interpreters for other languages, and even C++ compilers themselves. You can develop libraries for use in other languages, write games, price financial instruments, and much more besides. If you’ve ever typed make at a prompt, you were possibly using C++ without realizing it. C++ may power the browser that you are reading this on or may have been used to write device drivers for your machine.
This book will give you a firm grounding in a handful of C++ language and library features. Each chapter walks through a small, self-contained project, focusing on one area. Along with each chapter’s main feature, other parts of the language will be covered. For example, if you fill a container, such as a vector or an array, you may also want a way to display and manipulate its contents. Chapter two, therefore, focuses on vectors, but also introduces ranges and lambdas, as well as uses the format to display output. By gradually building up your repertoire, you will gain confidence, allowing you to rediscover the joy of C++. This book will focus on several fundamental parts, showing you various ways in which the language is now easier than it used to be. You will end up with a firm grounding, ready to use and learn more C++.
Why does C++ matter?
C++ is designed by a committee. Some languages are introduced and developed by a company or an individual. C++ is not. Working group 21 (WG21) of the International Organization for Standardization (ISO) is responsible for new versions of the language. You can find more details at https://isocpp.org/std. There’s been a newly ratified standard every three years since 2011, each adding new features and sometimes simplifying ways of doing things. This means there is a lot to learn. Some, but not all, documentation and descriptions sound as though there are written in legalese, which can be overwhelming. This book will use a few precise definitions to help you get the hang of parsing such explanations. Members of the committee make suggestions, write papers to explain their ideas and demonstrate how to implement new features or small improvements. This leads to innovations that influence other programming languages too. For example, Java and C# would not have generics if C++ hadn’t introduced templates. Ideas do flow in both directions. C++ also takes ideas from other languages, including functional programming idioms, such as lambdas.
These recent standards injected new life into C++ and caused lots of excitement. Companies that have been using C++ for years may previously have relied on in-house libraries to support features that are now part of the core language. Upgrading to use a newer standard can be hard work, but means that more people will be able to work on the code base without spending time getting up to speed with a niche implementation. As well as changes in technology stacks in businesses, there are now several conferences devoted to C++, along with podcasts and blogs. C++ has a reputation of being very hard-core, with geeks arguing about the difficult stuff and being mean to newbies (and each other). This is partially unfair, but the IncludeCpp group (https://www.includecpp.org/) makes an effort to be inclusive and welcoming. They have a discord group and tend to have a stall at C++ conferences too, so if you go alone, you can head straight to them and say hi. Recent changes have made several parts of C++ easier to explain and use, but have introduced more edge cases and complications. This book tries to stick with commonly available features that make your life easier, but it’s worth knowing a bit about some new, less widely supported features.
If you knew C++ before C++11, you might be intimidated by the changes. In fact, if you spent time catching up and blinked, you’ve still missed a lot. Fear not. It’s been said that C++ is like riding a bicycle: it hurts if you fall off—but C++ doesn’t have to be painful. This book will stop you from falling down rabbit holes. You can have fun and learn many approaches and paradigms, from object-oriented programming to functional approaches. A grounding in C++ will make other languages and approaches easier to understand too. Furthermore, C++ pervades so much that it will never go away, so it’s useful to understand a little. You’ll never know all of it. Bjarne himself is reputed to have said he’d rate himself as at seven out of ten on C++ knowledge, so fear not. To be a good programmer, you don’t have to know every detail of the language. Knowing enough as a basis to learn more is important. If you bootstrap your understanding now, you will also find it easier to keep up.
C++ has grown over time. Initially, C++ was C with classes, introducing the keyword new
(along with delete
and class
), and the idea of constructors and destructors. These are functions that run automatically when an object is created and when it goes out of scope or is deleted. Unlike garbage-collected languages, such as C# and Java, you have control over an object’s lifetime. Proponents of garbage-collected languages sometimes deride C++, claiming it’s all too easy to end up with memory leaks. Now, you don’t need to use new and delete, and C++ now has smart pointers to help with memory management. The language evolved over time, adding various new features. It still remains relatively compact, though it has grown since it began. Language, like all others, is what you make of it. You can write terrible code in any language. You can also write beautiful code in any language, but you need to learn how. By trying out code as you read this book, you will end up with some small programs to play with. They will cover various aspects of the language, giving you a firm grounding. You will see how C++ can be awesome.
There are many rivals to C++, yet C++ has staying power. It consistently remains near the top of the TIOBE index (https://www.tiobe.com/tiobe-index/#2022) and was in the top three for 2022. You could use C instead, but you will see stars (pointers being represented with an * character). If you want a data structure beyond an array, you’ll have to roll your own. You could use High-Performance Fortran for really, really fast computation. The UK Met Office uses Fortran for its weather modeling because they have a vast amount of data to crunch in a very short time. Fortran also loiters in many academic institutions, so you may have seen or used it if you are an academic or student. However, it is a little niche. You are more likely to come across some C++ code in the wider world.
Various new languages have been invented, aiming to deal with defects or annoyances of C++. D feels similar to C++, because of the C-like syntax and high-level constructs, and was invented to deal with aspects of C++ the creators didn’t like. Meanwhile, C++ continues to evolve, but always aims to remain backward compatible, so is constrained by historical decisions. New languages don’t have a legacy, so they have more freedom. Go, Objective C, Swift, Rust, and recently Carbon also rival C++ in some areas. That’s fine, and learning several languages and thinking about what might make a programmer’s life easier is a good thing. Many times, new ideas introduced into the latest C++ standards are based on insights from other languages. As new languages have been introduced, C++ still remains prevalent and often takes on board any challenges they present. C++ isn’t going away anytime soon. You can get involved and submit bug reports or suggestions too if you like. The committee consists of volunteers, who work hard to improve the language. IsoCpp gives details on how to get involved (https://isocpp.org/std/meetings-and-participation).
If you learn C++, you will have a solid foundation for other languages. The similarity to other languages can help you quickly pick up how to use them. You will get familiar with some data structures and algorithms, as well as various paradigms ranging from functional programming to object-oriented code. Even if you don’t end up on the standards committee or inventing your own programming language, you will be well placed to continue a journey of lifelong learning and understand what is happening under the hood.
Why read this book?
As the language evolves, people are writing books for each new standard and more general-purpose style guides. The style guides won’t make any sense if you don’t know the new features, and the new features build on previous changes, so the full details can be overwhelming. Where do you start in the face of a moving target? Where you are. You need a way to bootstrap your learning. This book will take you through some central changes via small projects so you have something to experiment with. By using some of the new features, you’ll be better able to recognize what modern C++ code is doing and know where to keep an eye out for further changes and evolutions.
Instead of reading a list of all the changes you may have missed, the ISOCpp website has a FAQ section (https://isocpp.org/wiki/faq) which gives an overview of some recent changes and big-picture questions. This website is run by the Standard C++ Foundation, a not-for-profit organization whose purpose is to support the C++ software developer community and promote the understanding and use of modern Standard C++. The site even has a section for people with a background in other languages who want to learn C++. It doesn’t, however, have a section for “Learning C++ if you already knew C++ a while ago.” This book plugs that gap. You don’t need a long list of every feature that’s been introduced over the years, you need just enough to get your confidence back.
You can keep an eye on the myriad and excellent resources online to stay aware of what has been and is changing in the language. ISOCpp will help you do this. However, you do need to stop and try things out in order to learn. Spending time experimenting will pay off, and this book will guide you to some useful experiments. Trying out features in bite-sized chunks will help you crystalize ideas and concepts. You will see alternative approaches from time to time. By seeing two ways to put items in a vector
, you will learn a new feature (the emplace methods) and recall an old feature (push_back
). This will help you read other people’s code and not be wrong-footed by unfamiliar approaches. You will learn how to think through alternatives, becoming aware of advice from different places, which sometimes conflicts. This book will take a pragmatic approach while encouraging you to think about alternatives.
How does this book teach C++?
This book covers a subset of features introduced into C++ from C++11 onwards. At the time of writing, C++23 is in feature-freeze, making it ready for a new standard. Each chapter focuses on one main feature, though introduces and uses other modern features and idioms too. Some people who used to know C++ well are put off by how many new things they will have to learn to start using it again, and beginners often get frightened off very quickly. It doesn’t have to be so hard. Getting up to speed now will make it easier to keep track as C++ continues to change and evolve. If you haven’t used C++ for a long time, and have seen other books going through an extensive list of all the new features and idioms but don’t know where to start or how to use them, this book will help you focus on some important parts, enabling you to dive into gnarly edge cases and thorough explanations elsewhere afterward.
This book will focus on self-contained projects using various parts of C++. You will try out some ideas and learn language features on the ride, rather than plow through each part of the language’s syntax and standard libraries using one-line examples. If you have gotten rusty, this book will give you a chance to practice and rediscover the joy of using C++. As you probably realize, writing a whole program gives you more practice than playing around with one or two lines. This book will, therefore, help you teach yourself.
Who this book is for
This book is aimed at people who have used a little, or even a lot, of the language and lost track of recent changes. If you recognize the syntax and want to try to learn more, you will gain something from this book. If you know what int x = 5; int & y=x
; do, have used a std::vector
before, and recognize std::cout << x
; you will be able to follow along. If you’ve seen int x{1}
; before, you’re part way there. If not, don’t panic. The curly braces are a new way to initialize almost everything, which you’ll soon get the hang of. If you used to know all the gnarly edge cases and quote chapter and verse of a previous standard, this book will help you focus on a handful of new features to help you get back in the driver’s seat. Once you’ve finished reading this book, you will know where to get an up-to-date compiler, how to keep an eye on upcoming changes and be able to read and write modern C++.
What you’ll learn from reading this book
You’ll learn how to use some new elements of the language, from ranges to random numbers, and learn several other, simpler ways of doing things on the journey. This book starts with a vector
, and builds up from there. Vectors are a good way to revise and then learn new features, including ranges, views, functors, and lambdas. Once you’re comfortable filling, displaying, querying, and manipulating a vector using ranges and algorithms, you’ll be ready to use other parts of the standard library including time (chrono
), random numbers, and finally coroutines.
Range-based for loops, introduced in C++11 made the language simpler. You can use them to walk over a container without needing to dive into iterators first. Over time full-blown ranges have become standard too, giving convenience, also avoiding the direct use of iterators, as well as giving more unified lookup and extra safety. Previously, it was possible to pass the start of one container and the end of another to an algorithm and not realize until something horrible happened at runtime. Ranges avoid that problem. You’ll become familiar with using ranges to view and copy the contents of a container.
You’ll find out how and why you don’t need so much boilerplate code in a class, by using the default
keyword for constructors and operators. You’ll learn how to use the new random number distributions. If you’re used to calling C’s rand
function, the new approach might seem complicated at first, but it’s powerful, and, when used properly, helps you avoid mistakes people often make, for example when simulating rolling dice or shuffling a deck of cards.
By using self-contained projects in each chapter, you’ll get the chance to use all kinds of new and old features. You’ll get to the point where you understand new features, knowing when and why to use them in an idiomatic way. Sometimes opinions differ on the best way to do things. The language’s evolution has taken us beyond arguing about brace placement (sorry in advance if you don’t like my chosen approach) and given us lots more to argue about. This book will give alternatives, firmly sitting on the fence when it comes to such discussions so that you can concentrate on trying to write some code and experiment with new ways of expressing yourself.
Summary
- C++ is everywhere and can be used for almost anything.
- C++ is evolving, with a new standard every three years, decided on by working group 21 (WG21) of the International Standard Organization of Standardization (ISO).
- C++ is a multi-paradigm language.
- You need a compiler that supports your chosen platform.
- Other similar languages are available, but C++ gives you a solid grounding in a variety of techniques and idioms.
- Coding a whole program is a great way to learn, and you’ll do just that in the rest of this book.
If you want to learn more about the book, check it out here.