LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 7

A mutable counter changed in a const function Answer, explanation & discussion

  • Output
  • Medium
  • 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 Sensor {
    int value_ = 42;
    mutable int reads_ = 0;
public:
    int read() const { ++reads_; return value_; }
    int reads() const { return reads_; }
};

int main() {
    const Sensor s;
    int sum = s.read() + s.read() + s.read();
    std::cout << sum << ' ' << s.reads() << '\n';
    return 0;
}
  • A 126 3 Correct
  • B 126 0
  • C 42 3
  • D Compilation error
Correct Answer: Option A

read is const, so it can be called on the const object, and the mutable reads_ may still be incremented inside it.

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