CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #129

A Half-Built Object Has No Destructor

hardExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <stdexcept>
3 
4class Log {
5public:
6 Log() { std::cout << "log opened\n"; }
7 ~Log() { std::cout << "log closed\n"; }
8};
9 
10class Server {
11 Log m_log;
12public:
13 explicit Server(int port) {
14 std::cout << "starting on port " << port << "\n";
15 if (port < 1024) {
16 throw std::invalid_argument("port is reserved");
17 }
18 std::cout << "server ready\n";
19 }
20 ~Server() { std::cout << "server stopped\n"; }
21};
22 
23int main() {
24 try {
25 Server good(8080);
26 std::cout << "using good server\n";
27 } catch (const std::invalid_argument& e) {
28 std::cout << "error: " << e.what() << "\n";
29 }
30 try {
31 Server bad(80);
32 std::cout << "using bad server\n";
33 } catch (const std::invalid_argument& e) {
34 std::cout << "error: " << e.what() << "\n";
35 }
36 return 0;
37}

🎯 Your Answer