ProgrammingHardGATE CS · TCS Digital · Advanced

What is printed? (C++17, assume <iostream> and using namespace std)

What is printed? (C++17, assume <iostream> and using namespace std)
struct T {
    T()  { cout << "c"; }
    ~T() { cout << "d"; }
};
int main() {
    {
        const T& r = T();
        cout << "1";
    }
    {
        T();
        cout << "2";
    }
}
  1. A. c1dcd2
  2. B. cd1cd2
  3. C. c1cd2d
  4. D. c1dc2d

Correct answer: A. c1dcd2

A temporary bound to a const reference lives as long as the reference (destroyed after '1'); an unbound temporary dies at the end of its full expression, before '2' is printed.

More OOP with C++ and Java questions

Exams that ask this topic