For which types of types (standard layout, POD, trivial type, alignment restrictions ...) are the following assumptions allowed?
Bis a subclass Aand B* bpointer to an object B.
A* a = bhas the same address as B, i.e.
static_cast<A*>(b) == reinterpret_cast<A*>(b)
B bs[n]is an array of objects B.
&bs[i] == static_cast<B*>(reinterpret_cast<unsigned char*>(bs) + i * sizeof(B))
offsetofcan be used to access data elements Aand B, from B:
int i = *static_cast<int*>(
reinterpret_cast<unsigned char*>(b) + offsetof(B, m_i));
EDIT: changed void*to unsigned char*for pointer arithmetic (with 1 byte unit)
tmlen source
share