All Good Things Must Come to an End

Test your C++ programming skills by solving the given puzzle about constructors with local state variables.

Puzzle code

Carefully read the code given below:

Press + to interact
#include <iostream>
#include <string>
struct Connection
{
Connection(const std::string &name) : name_(name)
{
std::cout << "Created " << name_ << "\n";
}
~Connection()
{
std::cout << "Destroyed " << name_ << "\n";
}
std::string name_;
};
Connection global{"global"};
Connection &get()
{
static Connection localStatic{"local static"};
return localStatic;
}
int main()
{
Connection local{"local"};
Connection &tmp1 = get();
Connection &tmp2 = get();
}

Your task: Guess the output

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

The possible console output lines are given below on the right side of the column. Place them in the correct sequence.

Drag and drop the cards in the blank spaces.


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.