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.
You can return a const pointer:
Note that I’ve also made the member-function const (the second
const), to tell the compiler that this member-function may be called onconstParticleinstances.Note: as you’ve already mentioned, a better solution is to use STL vectors and so on…