CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #147

The Member Built Before the Throw

mediumExceptions

Machine has a Part member and its constructor throws after the body starts. What is printed?

📄 Code

1#include <iostream>
2#include <stdexcept>
3 
4class Part {
5public:
6 Part() { std::cout << "part built\n"; }
7 ~Part() { std::cout << "part gone\n"; }
8};
9 
10class 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};
21 
22int 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}