Question 5
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
class Grid {
int cells_[3] = {1, 2, 3};
public:
int& at(int i) { std::cout << 'w'; return cells_[i]; }
int at(int i) const { std::cout << 'r'; return cells_[i]; }
};
int main() {
Grid g;
const Grid& view = g;
g.at(0) = 10;
int a = view.at(0);
int b = g.at(2);
std::cout << ' ' << a + b << '\n';
return 0;
}
- A wrw 13 Correct
- B wrr 13
- C www 13
- D wrw 4
Correct Answer: Option A
Calls on the non-const g choose the writable overload (w), calls through the const view choose the read-only one (r). The write through g is visible through view: 10 + 3 = 13.
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!