Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Offset of type in multiple inheritance

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);
}
like image 938
RobbinMarcus Avatar asked Sep 04 '25 17:09

RobbinMarcus


1 Answers

Use

reinterpret_cast<char *>(static_cast<A *>(&obj)) - reinterpret_cast<char *>(&obj);
like image 74
Java Man Tea Man Avatar answered Sep 07 '25 13:09

Java Man Tea Man