LearnFrenzy
Sign in Take a free test

Encapsulation · Find the Error · Question 5

Error: writing through a pointer-to-const getter Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

class Buffer {
    int data_[4] = {1, 2, 3, 4};
public:
    const int* data() const { return data_; }
    int size() const { return 4; }
};

int main() {
    Buffer b;
    int* p = b.data();
    p[0] = 99;
    std::cout << b.data()[0] << '\n';
    return 0;
}
  • A data_ must be a vector
  • B data() returns const int*, which cannot be converted to int* – the class only allows reading through this pointer Correct
  • C size must be static
  • D Arrays cannot be returned
Correct Answer: Option B

const int* p = b.data(); compiles, but then p[0] = 99 would be rejected. The const in the return type protects the internals.

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