3

Quoth the standard in [class.prop]/3:

A class S is a standard-layout class if it:

  • has the same access control for all non-static data members,

My understanding (and perhaps I'm mistaken) has always been that C++ access controls do not affect the physical layout of a class in any way -- they're purely a compile-time mechanism to enhance encapsulation. (Or to put it another way, changing a member from private to public is not an ABI-breaking change.)

If this is the case, then what is the reason for this restriction for standard-layout classes?

Community
  • 1
  • 1
Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82

1 Answers1

3

Access control very much does affect layout: Within one access contol level, the addresses of non-static data members increase in declaration order, but there is no requirement on addresses of different access levels with respect to one another.

Since standard layout is about addresses of members, the requirement ensures that all member addresses are in a well-defined order.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • IMO this just restates the data already in the question in a different way. The real question here is: given that access specifier are completely a compile-time thing just to generate error messages, why should they affect the binary layout in any way? What kind of help is the standard giving to implementors in allowing access declarators to affect the binary layout? – Matteo Italia Jan 07 '19 at 02:21
  • (more interestingly, is it just to allow opportunities to better pack stuff but allowing it only when it wouldn't impact compatibility with C, or is it formalizing some existing bizzarro implementation, that e.g. kept all private members at start?) – Matteo Italia Jan 07 '19 at 02:26
  • 3
    Well, you learn something new every day! Do any implementations actually reorder members based on access levels though? – Tristan Brindle Jan 07 '19 at 02:27
  • That's always the real question isn't it? There are many things a compiler "may" do, but it's sometimes hard to know if any actually do those things, especially something like this where unless you were really looking for it you most likely would not notice. – Retired Ninja Jan 07 '19 at 02:30