Sorry if this has been asked before, but I can't find a clear enough answer.
What is the correct way to provide public read-only access to an array member in C++?
if i have a class like the following:
class Particle
{
double _position[10];
public:
double* get_position()
{
return _position;
}
};
I guess is really bad to return a pointer to the array, since that means it can be changed at any time outside of the class, is it enough to return a const pointer instead?
I have seen other questions about the use of arrays in C++, and how is a better option to use vectors, nevertheless I'm really curious about this issue.
As you can see I'm only a C++ noob, sorry if this is a stupid question.
P.D. Sorry for my bad English.
Returning a const* isn't much better, as the caller can just cast the constness away.
Consider providing a const Iterator instead of returning a pointer. This gives users of your class access to positions without exposing the implementation details. If you later want to switch from a fixed-length array to a STL container, you can do so with no impact on users of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With