Assuming standard headers and using namespace std, what does this C++ code print? struct T { char c; T(char ch) : c(ch) { cout << c; } ~T() { cout << c; } }; int main() { T a(‘1’); T b(‘2’); }
Correct answer C. 1221
Explanation
Local objects are constructed in the order they are declared, so a prints 1 and then b prints 2. At the end of main they are destroyed in reverse order of construction, so b's destructor prints 2 before a's prints 1. This last-in, first-out destruction lets later objects safely depend on earlier ones.
Answer checked How we write and check questions
Discussion