0

In C++, if I declare a class/struct as thus:

struct Data
{
    int member0;
    int member1;
};

In most compilers, member0 appears earlier in the object representation than member1.

Does the standard mandate this behaviour, or is a compiler theoretically allowed to put member1 before member0 in the object representation?
What does the standard have to say about this, and where does it say it?
(I am interested in all standard versions if the mandated behaviour has changed at any point.)

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Pharap
  • 3,826
  • 5
  • 37
  • 51
  • 2
    Do you mean the in-memory layout of instances of the structure? – Some programmer dude Dec 07 '18 at 13:51
  • Do you want to know about this specific struct exactly, or are you looking for a more general answer? This specific example is easy, the general answer could almost be it's own book. – NathanOliver Dec 07 '18 at 13:54
  • *"Nonstatic data members of a (non-union) class with the same access control are allocated so that later members have higher addresses within a class object"* So yes, `member0` must appear earlier than `member1` – Cory Kramer Dec 07 '18 at 13:56
  • @CoryKramer This isn't a duplicate of that question, that question is asking about `dynamic_cast` and `reinterpret_cast`. – Pharap Dec 07 '18 at 15:07

1 Answers1

6

From [class.mem§19]:

Non-static data members of a (non-union) class with the same access control are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified. Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions and virtual base classes.

Since both of your members are public, member0 is guaranteed to be stored before member1.

Quentin
  • 62,093
  • 7
  • 131
  • 191