Practice mode C++

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.