← Back to Question List
C++ Quiz #147
The Member Built Before the Throw
Machine has a Part member and its constructor throws after the body starts. What is printed?
📄 Code
1#include <iostream>2#include <stdexcept>34class Part {5public:6 Part() { std::cout << "part built\n"; }7 ~Part() { std::cout << "part gone\n"; }8};910class Machine {11 Part m_part;12public:13 Machine(bool ok) {14 std::cout << "machine body\n";15 if (!ok) {16 throw std::runtime_error("assembly failed");17 }18 }19 ~Machine() { std::cout << "machine gone\n"; }20};2122int main() {23 try {24 Machine m(false);25 std::cout << "running\n";26 } catch (const std::exception& e) {27 std::cout << "caught: " << e.what() << "\n";28 }29 return 0;30}