Question 5
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
#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!