Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Encapsulating arrays

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.

like image 896
Mario Avatar asked Dec 13 '22 14:12

Mario


1 Answers

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.

like image 162
Aaron Saarela Avatar answered Jan 03 '23 08:01

Aaron Saarela