Question 12
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
class Door {
enum class State { closed, open, locked } s_ = State::closed;
public:
bool open() { if (s_ != State::closed) return false; s_ = State::open; return true; }
bool close() { if (s_ != State::open) return false; s_ = State::closed; return true; }
bool lock() { if (s_ != State::closed) return false; s_ = State::locked; return true; }
bool unlock() { if (s_ != State::locked) return false; s_ = State::closed; return true; }
};
int main() {
Door d;
std::cout << d.lock() << d.open() << d.unlock() << d.open() << d.lock() << d.close() << '\n';
return 0;
}
- A 101101 Correct
- B 111111
- C 110101
- D 100110
Correct Answer: Option A
closed → lock ✔ → open fails (locked) → unlock ✔ → open ✔ → lock fails (open) → close ✔. The private state can only change through these checked operations.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!