1

As far as I know, class and struct data is placed one variable after another, for example:

class Foo
{
    int A;
    char B;
    float* C;
    double* D;
};

Foo Object;
char* ptr = &Object;

&(Object.A) == ptr;    // all these are true
&(Object.B) == ptr+sizeof(int);
&(Object.C) == ptr+sizeof(int)+sizeof(char);
&(Object.D) == ptr+sizeof(int)+sizeof(char)+sizeof(float*);

Does it always work that way? Would it also work if I made all these data static in the class?

user23573
  • 2,479
  • 1
  • 17
  • 36
Avert
  • 435
  • 3
  • 17

1 Answers1

1

Well, the comments are a bit misleading, although all are correct. (Perhaps because this is in fact a duplicate of an old question)

Your original assumption is "basically" correct. Well, basically.

The only thing you can (at least most of the time) rely on is the order of the elements.

The actual size of the elements varies greatly across platforms and compilers. This is an issue of itself, but an int is most of the time 32bit but sometimes 16bit or even 64bit.

On top of that the compilers may (or may not) add some padding in between the elements, sometimes depending on the element type, sometimes not.

In conclusion: if you write code that depends on pointer arithmetic like the one you proposed, your code will be platform dependent and implementation/compiler dependent.

Community
  • 1
  • 1
user23573
  • 2,479
  • 1
  • 17
  • 36