Discussion: Who’s Up First?
Execute the code to understand the output and gain insights into constructors.
We'll cover the following...
Run the code
Now, it’s time to execute the code and observe the output.
Press + to interact
#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 ...