LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 5

const and non-const accessors on const and non-const objects Answer, explanation & discussion

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

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

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links