Search⌘ K

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.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
struct Resource
{
Resource()
{
std::cout << "Resource constructed\n";
}
};
struct Consumer
{
Consumer(const Resource &resource)
{
std::cout << "Consumer constructed\n";
}
};
struct Job
{
Job() : resource_{}, consumer_{resource_} {}
Consumer consumer_;
Resource resource_;
};
int main()
{
Job job;
}

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 ...