ProgrammingVery hardProduct-company placement · C++

What is printed?

What is printed?
struct T { T() { cout << "c"; } ~T() { cout << "d"; } };
int main() {
    T();
    cout << "1";
    const T& r = T();
    cout << "2";
}
  1. A. c1c2dd
  2. B. cd1cd2
  3. C. c1dc2d
  4. D. cd1c2d

Correct answer: D. cd1c2d

A temporary is destroyed at the end of the full expression that created it, so the first T dies before 1 is printed. Binding a temporary to a const reference extends its lifetime to the reference's scope, so it dies after 2.

More OOP with C++ and Java questions

Exams that ask this topic