I want to store vertices data of a mesh in a class. Each instance has an array of floats and is accessible via a getter that returns the array pointer. The data of the array should be const, as well as the array itself. So my first thought was to declare the member this way:
const float * const m_vertices; // const pointer to const floats
the problem is that the actual data is not know at compile time (loaded from a file, procedurally generated...)
Is there a way to ensure the data will be left untouched except when it's initialized (in the constructor for instance)?
EDIT : I tried what joseph proposed :
//Mesh class
Mesh::Mesh(const float *vertices)
: m_vertices(vertices)
{
}
//creation of data
int size = 10; //this can't be const because the number of vertices is not known at compile time
float arr[size]; //error : "size" is not const
for (int i = 0; i < 10; i++) {
arr[i] = i;
}
Mesh m = Mesh(arr); //this apparently works... But the constructor is expecting a const float *. Here i'm giving a float *. Why does this works ?
constmember of a class, and the actual pointer or array a private member that can be initialised at run time (e.g. in the constructor of the class). Ensure you don't provide any other non-constfunction that provides access to the data. Also, you'll probably need t means of storing the number of elements, and accessing that number.const float *. That prevents changing the data.const float *effectively tells the compiler that the pointed-tofloat(orfloats) should not be modified. Afloat *tells the compiler that modifying thefloatdata is permitted. Now, taking afloat *and adding a proviso of "shall not modify" does no harm - so there is no need to prevent it. Going the other way (removingconst) permits modification of something that should not be modified (i.e. stops the compiler diagnosing the attempt as an error).