This type of struct always has the same size. This is a warranty from the Standard. When you define a struct , you say: "I have an object of this size (the sum of the sizes of the members + a possible complement for alignment for each member), and they should be in that order in memory (the same order of the definitions of the members in the definition of the struct )":
(N4296) 9.2
/ 12 [ Example: A simple example of a class definition is
struct tnode { char tword[20]; int count; tnode* left; tnode* right; };
which contains an array of twenty characters, an integer and two pointers to objects of the same type. [...] -end example
/ 13 Non-stationary data members of a (non-unitary) class with the same access control (section 11) are allocated so that later members have higher addresses in the class object. The distribution order of non-static data elements with different access control is not specified (clause 11). Requirements for alignment of the implementation can lead to the fact that two neighboring elements will not be distributed immediately one after another; therefore, space may be required to manage virtual functions (10.3) and virtual base classes (10.1).
Note " with the same access control qualifier ." If your structure has a data set with different access specifiers, the layout may not be what you might expect, except for a guarantee that would give something like:
public: some_type public_1; private: some_type private_1; public: some_type public_2;
public_2 will have a higher address than public_1 . In addition, unspecified. private_1 can be at a lower or higher address.
Regarding your other question (asked in the comments):
Would it be better to use a class instead of a structure?
In C ++, a struct and class are essentially the same, the only difference is that the members (and inheritance) of the default struct are public , while with class they are private by default. This is made even clearer in the note and example of the standard:
Β§3.1. Declarations and Definitions [basic.def]
/ 3 [ Note: In some cases, C ++ implementations implicitly define the default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8) or destructor (12.4 ) -end note ] [ Example: given
the implementation will implicitly define functions to make the definition of C equivalent
struct C { std::string s; C() : s() { } C(const C& x): s(xs) { } C(C&& x): s(static_cast<std::string&&>(xs)) { }
-end example ]
Note that the example from the standard uses struct rather than class to illustrate this point for non-POD structs . This is even more clear when you consider that the definition of struct in the standard is given in Section 9, Classes.