I have several questions to ask that pertains to data position and alignment in C++. Do classes have the same memory placement and memory alignment format as structs?
More specifically, is data loaded into memory based on the order in which it’s declared? Do functions affect memory alignment and data position or are they allocated to another location? Generally speaking, I keep all of my memory alignment and position dependent stuff like file headers and algorithmic data within a struct. I’m just curious to know whether or not this is intrinsic to classes as it is to structs and whether or not it will translate well into classes if I chose to use that approach.
Edit: Thanks for all your answers. They’ve really helped a lot.
The memory placement/alignment of objects is not contingent on whether its type was declared as a
classor astruct. The only difference between aclassand astructin C++ is that a class haveprivatemembers by default while a struct havepublicmembers by default.I’m not sure what you mean by “loaded into memory”. Within an object however, the compiler is not allowed to rearrange variables. For example:
The variables
cmust be located afterbandbmust be located afterawithin aFooobject. They are also constructed (initialized) in the order shown in the class declaration when aFoois created, and destructed in the reverse order when aFoois destroyed.It’s actually more complicated than this due to inheritance and access modifiers, but that is the basic idea.
Functions are not data, so alignment isn’t a concern for them. In some executable file formats and/or architectures, function binary code does in fact occupy a separate area from data variables, but the C++ language is agnostic to that fact.
Memory alignment is something that’s almost automatically taken care of for you by the compiler. It’s more of an implementation detail than anything else. I say “almost automatically” since there are situations where it may matter (serialization, ABIs, etc) but within an application it shouldn’t be a concern.
With respect with reading files (since you mention file headers), it sounds like you’re reading files directly into the memory occupied by a
struct. I can’t recommend that approach since issues with padding and alignment may make your code work on one platform and not another. Instead you should read the raw bytes a couple at a time from the file and assign them into thestructs with simple assignment.