Question 7
Back to Exercise
What is the output of the following C++ program?
#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!