Data Member Initialization in Modern C++
Data Member Initialization in Modern C++
Constructors, Destructors, Non-static Data Member Initialization, Inline Variables, Designated Initializers, and More Modern C++ Features. A not-only-beginner approach.
About the Book
Throughout this book, you will learn practical options to initialize data members in Modern C++. More specifically, this text teaches various types of constructors, non-static data member initialization, inline variables, designated initializers, and more. Additionally, you’ll see the changes and new techniques from C++11 to C++20 and lots of examples to round out your understanding.
The goal of this book is to equip you with the following knowledge:
- The basic rules of data members and constructors.
- Essential information about copy constructors, move constructors and destructors.
- How to efficiently initialize non-static data members using C++11 features like non-static data member initialization, inheriting, and delegating constructors.
- How to streamline working with static data members with inline variables from C++17.
- How to work with container-like member, non-copyable data members like `const` data members or move-able only data members.
- Aggregates and Designated initializers from C++20.
The book contains 15 chapters in the following structure:
- Chapters 1 to 5 create a foundation for the rest of the book. They cover constructors, destructors, and the basics of data members.
- Chapter 6 shows a use case for passing strings into constructors.
- Chapter 7 is a short quiz on constructors. You can check your knowledge from the first "part" of the book.
- Chapter 8 describe Non-static Data Member Initialization (NSDMI), a powerful feature from C++11 that improves how we work with data members.
- Chapter 9 serves as a practical summary for NSDMI, where you can solve a few exercises.
- (In progress) Chapter 10 discusses how to initialize container-like data members.
- (In progress) Chapter 11 contains information about non-regular data members and how to handle them in a class. You'll learn about `const` data members, `unique_ptr` as a data member, and references.
- Chapter 12 shows how `inline` variables from C++17 work.
- Chapter 13 moves to C++20 and describes Designated Initializers, a handy feature based on similar thing from the C language.
- Chapter 14 it's the summary chapter with a demo that gathers most of the features described in the book.
- Chapter 15 is the final quiz with seven questions ranging from constructors to designated initializers.
Most sections are completed, but I'm still working on filling two chapters and polishing the quality.
Who is this book for?
The book is intended for beginner/intermediate C++ programmers who want to learn how to work with static and non-static class data members in Modern C++ (from C++11 to C++20).
You should know at least some of the basics of creating and using custom classes.
This text is also helpful for experienced programmers who know older C++ standards and want to move into C++17/C++20
Bundles that include this book
Reader Testimonials
Jonathan Boccara
(fluentcpp.com)
A new thorough and practical book from Bartek that will take you by the hand and give you an in-depth understanding of a core aspect of C++. The book starts with simple examples and then guides you through various aspects of constructors, and different kinds of data members. I like that it addresses the latest features of C++, including C++20.

Andreas Fertig
andreasfertig.info
Data Member Initialization in Modern C++ gives you an excellent overview of how to initialize class members. I like the practical examples, detailed overview, and discussions of various techniques for custom types design.
Table of Contents
-
About the Book
- Why should you read this book?
- Learning objectives
- The structure of the book
- Who is this book for?
- Prerequisites
- Reader feedback & errata
- Example code
- Code license
- Formatting
- Special sections
- About the Author
- Acknowledgements
- Revision History
-
1. Simple Types and Data Members
- Basics
- Setting values to zero
- Initialization with aggregates
- Default data member initialization
- Summary
-
2. Classes and Initialization With Constructors
- A simple class type
- Basics of constructors
- Body of a constructor
-
Adding constructors to
DataPacket
- Compiler-generated default constructors
- Explicit constructors
- Difference between direct and copy initialization
-
Using
explicit
for strong types - Constructor summary
-
3. Copy and Move Constructors
- Copy constructor
- Move constructor
- Distinguishing from assignment
- Adding logging to constructors
- Copy and swap idiom
- Trivial classes and user-declared/user-provided default constructors
-
4. Delegating and Inheriting Constructors
- Delegating constructors
- Limitations
- Inheritance
- Inheriting constructors
-
5. Destructors
- Basics
- Objects allocated on the heap
- Destructors and data members
- Virtual destructors and polymorphism
- Partially created objects
- A compiler-generated destructor
- Summary and use cases
-
6. A Use Case - Best Way to Initialize
string
Data Members - 7. Quiz on Special Member Functions
-
8. Non-Static Data Member Initialization
- How it works
- Investigation
- Experiments
- Other forms of NSDMI
- Copy constructor and NSDMI
- Move constructor and NSDMI
- C++14 changes
- C++20 changes
- Limitations of NSDMI
- NSDMI: Advantages and Disadvantages
- NSDMI summary
-
9. NSDMI: Exercises
- The first exercise
- The second exercise
-
10. Containers as Data Members
- The basics
-
Using
std::initializer
list - Example implementation
-
11. Non-regular Data Members
- Constant non-static data members
- References as data members
- Pointers as data members
- Moveable-only data members
- Summary
-
12. Inline Variables in C++17
- About static data members
- Motivation for inline variables
- Exercise for inline variables
- Global inline variables
- Constexpr and inline variables
-
13. Aggregates and Designated Initializers in C++20
- Aggregates in C++20
- The basics of Designated Initializers
- Rules
- Advantages of designated initialization
- Examples
- Summary
-
14. Summary of Class Data Members
- The summary example
- Compiler support
- 15. The Final Quiz
-
Appendix A - Quiz and Exercises Answers
- The quiz after Inheriting Constructors
- The final quiz
- Solution to the first coding problem
- Solution to the second coding problem
- Solution to the third coding problem
- References
- Notes
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
Do Well. Do Good.
Authors have earned$11,716,512writing, publishing and selling on Leanpub, earning 80% royalties while saving up to 25 million pounds of CO2 and up to 46,000 trees.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers), EPUB (for phones and tablets) and MOBI (for Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
Recipes for Decoupling
Matthias NobackWrite software that survives
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
CQRS by Example
Carlos Buenosvinos, Christian Soronellas, and Keyvan Akbary- Leverage your Software Architecture skills by learning everything about CQRS in detail with lots of examples
- Develop faster applications by applying CQRS and fostering Read Models and Projections
- Learn how to apply CQRS into a brownfield project from a pragmatic approach
C++20 - The Complete Guide
Nicolai M. JosuttisAll new language and library features of C++20 (for those who know previous C++ versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
Jetpack Compose internals
Jorge CastilloJetpack Compose is the future of Android UI. Master how it works internally and become a more efficient developer with it. You'll also find it valuable if you are not an Android dev. This book provides all the details to understand how the Compose compiler & runtime work, and how to create a client library using them.
Maîtriser Apache JMeter
Philippe Mouawad, Bruno Demion (Milamber), and Antonio Gomes RodriguesToute la puissance d'Apache JMeter expliquée par ses commiteurs et utilisateurs experts. De l'intégration continue en passant par le Cloud, vous découvrirez comment intégrer JMeter à vos processus "Agile" et Devops.
If you're looking for the newer english version of this book, go to Master JMeter : From load testing to DevOps
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
The PowerShell Scripting and Toolmaking Book
Don Jones and Jeff HicksLearn the patterns, practices, and details of PowerShell Scripting and Toolmaking from the industry's two most recognized experts on the subject.
Mastering STM32 - Second Edition
Carmine NovielloWith more than 1200 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the most complete guide around introducing the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL and STM32CubeIDE development environment.
Introduction to Data Science
Rafael A IrizarryThe demand for skilled data science practitioners in industry, academia, and government is rapidly growing. This book introduces concepts from probability, statistical inference, linear regression and machine learning and R programming skills. Throughout the book we demonstrate how these can help you tackle real-world data analysis challenges.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #6
All the Books of The Medical Futurist
6 Books
We put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy, digital health investments and how technology giants such as Amazon...