LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 7

An object that enforces its own rules Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following C++ program?

main.cpp
#include <iostream>

class Ticket {
    int seats_left_ = 3;
public:
    bool book(int n) {
        if (n <= 0 || n > seats_left_) return false;
        seats_left_ -= n;
        return true;
    }
    int left() const { return seats_left_; }
};

int main() {
    Ticket t;
    std::cout << t.book(2) << t.book(2) << t.book(1) << t.book(0) << ' ' << t.left() << '\n';
    return 0;
}
  • A 1010 0 Correct
  • B 1110 0
  • C 1011 0
  • D 1010 1
Correct Answer: Option A

The second booking of 2 fails because only 1 seat is left; the booking of 1 succeeds; 0 seats is invalid. Callers cannot overbook because they never touch seats_left_ directly.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links