Search code examples
c++objectmemorylanguage-lawyerstandards

What does the standard say about the order of member variable declarations?


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.)


Solution

  • 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.