The short version of this question: Does a pointer to the first data member of a class result in a pointer to all its data members?
Discussion:
I'm reading some sample code, and this is interesting. When a particular function (in this case the glUniformMatrix4fv
C function from OpenGL) takes as a parameter an array, this is passed in the common C way of using a pointer to the address of the array's first element, as follows:
glUniformMatrix4fv(glvariable, 1, 0, &newmatrix[0]);
// referring to newmatrix
This developer has a C++ class for creating a 4X4 matrix, for a total of 16 floats. However, the data members of that class are divided into 4 separate vectors of 4 data members each:
Here are the data members of the class:
vec4 x;
vec4 y;
vec4 z;
vec4 w;
The vec4
class in turn provides these data members:
T x;
T y;
T z;
T w;
He then creates a function to point to just the first vec4 x
data member:
const T* Pointer() const
{
return &x.x;
}
And somehow, this miraculously translates into sending all 4 vec4
objects and their respective 4 components:
glUniformMatrix4fv(modelviewUniform, 1, 0, modelviewMatrix.Pointer());
I'm fairly new to C++ but this surprised me that you can point to just one data member and expect all the rest to get sent as well. Is it because the class defines them in a particular order? What if they had been defined in a different order in the class definition?
This is the C++ object model. You're guaranteed that within the same access level (
private
/public
/protected
), the object properties are in order (C++11), and the same for members without access specifiers between them (in C++03).This doesn't mean what you're doing is a good idea. It's better to avoid the cast and just have the function do some more work.
C++11:
9.2 Class members [class.mem]
C++03
9.2 Class members [class.mem]