All Good Things Must Come to an End
Test your C++ programming skills by solving the given puzzle about constructors with local state variables.
We'll cover the following
Puzzle code
Carefully read the code given below:
#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.
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.