Click to See Complete Forum and Search --> : memory allocation for a struct


c94wjpn
February 26th, 2003, 03:38 AM
If I define

struct A
{
float x,y,z;
A(xx,yy,zz) { x=xx;y=yy;z=zz;};
virtual ~A(void) {};
}

then

A a(0.0,1.0,2.0);
float* p2;

p2 = reinterpret_cast<float*>(&a);

float f;
f = p2 [2];

assert(f==a.z);

Can I be certain that the member variables of A will appear in memory in the right order like an array, in spite of the fact that A has a virtual function table? Is this part of the C++ spec? Is it true of all platforms and implementations?

Paul McKenzie
February 26th, 2003, 05:13 AM
Originally posted by c94wjpn
Can I be certain that the member variables of A will appear in memory in the right order like an array, in spite of the fact that A has a virtual function table?I don't have the ANSI/ISO spec on hand, but classes / structures with user-defined destructors (and consstructors) have no guarantees where the first member is located.

Why not use an array in the structure instead of three separate float variables? Then you just define a member that returns the address of the array, or define an operator float*()

struct A
{
float coord[3];
A(float xx,float yy,float zz) { coord[0]=xx; coord[1]=yy;coord[2]=zz;};
virtual ~A(void) {};
float *GetCoords() { return coord; }
operator float*() { return coord; }
};

int main()
{
A MyA(1.0,2.0,3.0);
float *p = MyA; // No need to cast
}

Regards,

Paul McKenzie

dimm_coder
February 26th, 2003, 05:39 AM
Don't know about what the ANSI standart says
about all this, but when I use something like this

struct foo
{
int a;
int b;

foo( int _a, int _b ) : b(_b), a(_a) {}
};

my linux gc++ gives a warning and says
to initialize a struct members in the order by
wich they were declared, like

foo( int _a, int _b ) : a(_a), b(_b) {}

And as I ussulay saw, members of classes(structs)
has a order in the memory like they were declared
in the definition (a, b).

About virual functions. Ussualy if class has
some virtual function, then object has a
vtbl pointer before data members in the memory.
So of so and a object of this struct has a vtbl,
so p[0] = vtbl, and only then data members are stored.

But I want to notice that it is nothing about this in the standart.
It depends of compiler wich generate a code.

Richard.J
February 26th, 2003, 06:07 AM
This warning just says that the member variables are initialized in the order they appear in the class definition and not in the order that you use.
I. e.

struct foo
{
int a;
int b;

foo( int _a, int _b ) : b(_b), a(_a) {}
};


does not imply that the constructor for b is called before the constructor for a, but vice versa due to the definition order for a and b;