Basic rules: 1. The natural boundary of each data member is its byte size (char is 1,short to 2,int to 4) and is aligned according to its natural boundary; 2. The total natural boundary of the entire object is the natural boundary of the largest data memeber, The total size must be a multiple of the total natural boundary (typically 1,2,4,8). 3. The size of the empty class is 1;
Example: struct S{char c;double i;int j;};
sizeof (S) is: 1+ complement 7+8+4=20, the total boundary is 8, the total size must be a multiple of 8, 4, and finally 24;
Class D{char I; S K;int J;};
sizeof (D) is: 1+ 7 (S boundary is 8) +24+4 = 36, total boundary is 8, complement 4, final 40;
Consider inheritance: 1. The member function does not occupy the memory of object, and multiple objects share a function that is stored in the code segment. 2. If virtual function exists in class, the memory at the beginning of each object will be placed with a copy of the pointer (vbptr) pointing to virtual function table (VTBL). 3. If the virtual inheritance is from base class, a copy of the pointer (VFPTR) will be placed at the beginning of the drive class object to point to the beginning of the base class in Obejct.
Memory space layout for C + + object