Does the C++ standard dictate the compilation layout of the class and struct? How are they compiled differently especially if they are empty?
Asked
Active
Viewed 404 times
7
-
Absolutelu "no" on both counts to the first question. A class has an implicit "this" pointer in answer to the second question. – paulsm4 Jun 04 '12 at 20:52
-
11@paulsm4: Your answer to the second question is wrong. there is no dofference between a `class` and a `struct` in this regard. To wit, a `struct` can have `virtual` members. – John Dibling Jun 04 '12 at 20:53
-
5Classes and structs are the exact same thing, the only difference is with default access specification (for members and bases). – GManNickG Jun 04 '12 at 20:53
-
@paulsm4 If there is no code there is nowhere for the implicit 'this' pointer to be generated. – user207421 Jun 04 '12 at 23:22
1 Answers
13
It does in a way, it says that it has to allocate space for it unless certain cases when its used as a base class (known as Empty Base Class Optimization). This is to guarantee that different objects have different addresses.
They are compiled the same given that struct
and class
are the same thing, except for the default access specifier. In C++11 the notion of standard-layout classes/structs is introduced, and guarantees that the memory layout for empty classes to be the same.

K-ballo
- 80,396
- 20
- 159
- 169
-
1Is it specified anywhere how much space is allocated? 1 byte? – Sebastian Hoffmann Jun 04 '12 at 20:51
-
2@Paranaix: As far as I know, is not specified. It could be more than 1 byte to satisfy alignment requirements. – K-ballo Jun 04 '12 at 20:53
-
The size of reference would be architecture dependant. One address on x86 would be 32 bits. – starbolin Jun 04 '12 at 20:58
-
I thought they added char to an empty class and performed alignments depending on the architecture? – unj2 Jun 04 '12 at 21:10
-
@kunj2aan: Sounds like a sensible implementation, but the standard does not mandate it. – K-ballo Jun 04 '12 at 21:11
-
@Paranaix: Take a look at my similar question, http://stackoverflow.com/questions/8271673/can-there-be-a-c-type-that-takes-0-bytes – Linuxios Jun 04 '12 at 21:21
-