I read that if you declare two such structures:
struct Node { int a, b, c; }; struct DerivedNode { struct Node base; int d, e, f; };
Then you can use pointers for them as follows:
struct DerivedNode myDerivedNode; struct Node *regularNode = (struct Node *) &myDerivedNode; regularNode->a = 3;
In other words, the address offsets for a, b, c same within the struct Node and struct DerivedNode . That way, you can get a kind of polymorphism from where you can force the (struct Node *) -cast pointer to the DerivedNode pointer wherever the Node pointer will normally execute.
My question is whether this behavior is guaranteed. I know that there are some strange problems with memory alignment and that the compiler sometimes reorders fields to achieve better memory packing. Will the base field be anywhere but the start of the struct DerivedNode ?
Brian gordon
source share