Who’s Up First?

Test your C++ programming skills by solving the given puzzle about constructors.

Puzzle code

Carefully read the code given below:

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;
}

Your task: Guess the output

Try to guess the output of the above code. Attempt the following quiz to assess your understanding.

Q

What is the expected output of the above code?

A)
Consumer constructed
Resource constructed
B)
Resource constructed
Consumer constructed
C)
Resource constructed
Consumer constructed
Resource constructed
D)
Resource constructed
Consumer constructed
Consumer constructed
Resource constructed

Let’s discuss this code and output together in the next lesson.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.