I have the following structure in C++
struct A {
int a;
double b;
float c;
}
Is there a difference in memory layout between this struct and one with a function added to it?
struct B {
int a;
double b;
float c;
void foo();
}
B::foo() { //do stuff }
The C++ standard guarantees that memory layouts of a C struct and a C++ class (or struct -- same thing) will be identical, provided that the C++ class/struct fits the criteria of being POD ("Plain Old Data"). So what does POD mean?
A class or struct is POD if:
All data members are public and themselves POD or fundamental types (but not reference or pointer-to-member types), or arrays of such
So yes in your case, the memory layout is the same.
Source: Structure of a C++ Object in Memory Vs a Struct
Is there a difference in memory layout between this struct and one with a function added to it?
Since A
and B
are standard layout1, and their common initial sequence consists of every non-static data member2, they are layout-compatible.
The Standard only describe the semantics of an abstract machine, so there is no guarantee an object of type A
will be represented in memory as an object of type B
, but layout-compatible types tend to be.
1)[class]/7
A standard-layout class is a class that:
- has no non-static data members of type non-standard-layout class (or array of such types) or reference,
- has no virtual functions (10.3) and no virtual base classes (10.1),
- has the same access control (Clause 11) for all non-static data members,
- has no non-standard-layout base classes, either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
- has no base classes of the same type as the first non-static data member.
2)[class.mem]/21
& [class.mem]/22
Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout compatible types (3.9).
It formally depends on your compiler, but a compiler where declaring a non-virtual member function changes the layout of the class would be borderline sabotage. You need this kind of stability to enforce the compatibility on which shared objects rely on every platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With