Reputation: 9090
For which categories of types (standard layout, POD, trivial type, alignment constraints...) are the following assumptions valid?
B
is a subclass of A
, and B* b
a pointer to a B
object.
A* a = b
has the same address as b
, i.e.
static_cast<A*>(b) == reinterpret_cast<A*>(b)
B bs[n]
is an array of B
objects.
&bs[i] == static_cast<B*>(reinterpret_cast<unsigned char*>(bs) + i * sizeof(B))
offsetof
can be used to access data members of A
and of 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)
Upvotes: 4
Views: 156
Reputation: 477040
If A
and B
are both standard-layout and b
points to a most-derived object of class B
, then the first assertion should be true.
The offsetof
macro can be used on members of standard-layout types.
The second point of the question is true for any type B
because that's how arrays are defined.
Upvotes: 4