Discussion: Who’s Up First?
Understand the order in which C++ initializes and destroys class members, regardless of their order in constructors. Explore how this impacts dependencies between objects and can lead to undefined behavior if not properly managed. Learn best practices for writing consistent and portable code by aligning member declarations with initializer lists and enabling compiler warnings across multiple compilers.
We'll cover the following...
Run the code
Now, it’s time to execute the code and observe the output.
Understanding the output
The Job class has two members, consumer_ and resource_, declared in that order. However, in the constructor’s member initializer list (the : resource_{}, consumer_{resource_} part), they are initialized in the opposite order. In which order are they actually initialized?
Member initialization in C++
C++ always initializes members in the order they are declared in the class, not in the order they are listed in the constructor’s member ...