GeeYouEye said:
I know that in straight C, the address of a struct is the address of the first member thereof. My situation is that I have an array of structs, each of which contains a single data member, an array (fixed-size)of characters. The question is, since in C++ structs are a special case of classes apparently (read that on cplusplus.com), can I still depend on the member memory to be consecutive, and is there any class overhead at the beginning or end of the struct that I have to worry about if I want to use pointer arithmetic go through the array?
In C++ memory representation of struct and class objects without virtual functions is identical to C representation of struct.
Objects of classes that have at least one virtual function contain an additional hidden data member called vptr. Vptr points to the vtbl -- a per-class table of the virtual functions' addresses.
Following test program illustrate this point:
// g++ struct_size.cc -o xstruct_size && ./xstruct_size
#include <stdio.h>
struct S1 {
int x;
};
class C1 {
public:
int x;
};
class C2 {
public:
int x;
virtual void vf() { ++x; }
};
struct MemoryLayoutOfC2 {
void* vptr; // gcc version 3.3 20030304 (Apple Computer, Inc. build 1666)
// places the vptr as the first data member of the object
int x;
};
int main(int argc, char** argv)
{
printf("Sizes of S1: %lu C1: %lu C2: %lu\n", sizeof(S1), sizeof(C1), sizeof(C2));
C2 c2;
printf("Address c2 obj: %p and c2.x member: %p\n", &c2, &c2.x);
return 0;
}
Following is an output of this program:
mac:~/play/$ g++ struct_size.cc -o xstruct_size && ./xstruct_size
Sizes of S1: 4 C1: 4 C2: 8
Address c2 obj: 0xbffffbc0 and c2.x member: 0xbffffbc4
Object of c2 have an additional hidden member - vptr that occupies extra four bytes. struct MemoryLayoutOfC2 shows actual memory layout of C2 object.
For additional details check any good paper that describes C++ object model, for example:
-
http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=195
- or book by Stanley B. Lippman: Inside the C++ Object Model