LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 19

A failed operation leaves the object unchanged Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

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

main.cpp
#include <iostream>
#include <optional>
#include <vector>

class History {
    std::vector<int> pages_;
public:
    void visit(int p) { pages_.push_back(p); }
    std::optional<int> back() {
        if (pages_.size() < 2) return std::nullopt;   // nothing to go back to: change nothing
        pages_.pop_back();
        return pages_.back();
    }
    std::size_t depth() const { return pages_.size(); }
};

int main() {
    History h;
    h.visit(1); h.visit(2); h.visit(3);
    auto a = h.back();
    auto b = h.back();
    auto c = h.back();
    std::cout << a.value_or(-1) << b.value_or(-1) << c.value_or(-1) << ' ' << h.depth() << '\n';
    return 0;
}
  • A 21-1 1 Correct
  • B 210 0
  • C 321 0
  • D 21-1 0
Correct Answer: Option A

Going back from 3 gives 2, then 1. The third call cannot go back (only one page left), so it returns nothing and leaves the history as it was – a failed operation must not damage the invariant.

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