LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 8

A mutable cache inside a const function Answer, explanation & discussion

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

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

main.cpp
#include <iostream>
#include <string>

class Document {
    std::string text_;
    mutable int cached_words_ = -1;
    mutable int computations_ = 0;
public:
    explicit Document(std::string t) : text_(std::move(t)) {}
    int words() const {
        if (cached_words_ < 0) {
            ++computations_;
            cached_words_ = 1;
            for (char c : text_) if (c == ' ') ++cached_words_;
        }
        return cached_words_;
    }
    void append(const std::string& t) { text_ += t; cached_words_ = -1; }
    int computations() const { return computations_; }
};

int main() {
    Document d("learn cpp daily");
    int a = d.words(), b = d.words();
    d.append(" now");
    int c = d.words();
    std::cout << a << b << c << ' ' << d.computations() << '\n';
    return 0;
}
  • A 334 2 Correct
  • B 334 3
  • C 333 1
  • D 344 2
Correct Answer: Option A

The first call computes and caches 3; the second uses the cache. append changes the text and invalidates the cache, so the next call recomputes (4). Two computations in total.

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