I'd like to know if it's possible to find the offset of a structure in an object with multiple inheritance without knowing any members of any type. I do know the types, if that helps.
I'm currently calculating offsets using sizeof()
. Problems exist when I have an empty base class, or padding is added when combining two classes for multiple inheritance.
Let me show the problem using an example:
struct A { int x; };
struct B { bool b; }; // Empty struct gives same results
struct C : B, A {};
int main()
{
// Prints: 4 1 8
printf("%i %i %i\n", sizeof(A), sizeof(B), sizeof(C));
C obj;
obj.x = 1;
obj.b = true;
// Simple offset calculations, I can't use these because they both use data members
// Prints: 4 4
printf("%i %i\n", (int)&obj.x - (int)&obj, offsetof(C, x));
// Cast to pointer
char* ptr = reinterpret_cast<char*>(&obj);
A* wrong = reinterpret_cast<A*>(ptr + sizeof(B));
// Prints wrong values because sizeof(B) == 1 wrongly offsets the pointer
printf("%i\n", wrong->x);
// Because of padding this is correct
// Empty base class optimization would simply cast ptr as correct
// How to get the correct offset?
A* correct = reinterpret_cast<A*>(ptr + 4);
// Prints correct value, 1
printf("%i\n", correct->x);
}
Use
reinterpret_cast<char *>(static_cast<A *>(&obj)) - reinterpret_cast<char *>(&obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With