I have:
class Foo {
int a;
int b;
std::string s;
char d;
};
Now, I want to know the offset of a, b, s, d given a Foo*
I.e. suppose I have:
Foo *foo = new Foo();
(char*) foo->b == (char*) foo + ?? ; // what expression should I put in ?
I don't know exactly why you want the offset of a member to your struct, but an offset is something that allows to to get a pointer to a member given the address of a struct. (Note that the standard offsetof macro only works with POD-structs (which yours is not) so is not a suitable answer here.)
If this is what you want to do, I would suggest using a pointer-to-member as this is a more portable technique. e.g.
int main()
{
int Foo::* pm = &Foo::b;
// Pointer to Foo somewhere else in the program
extern Foo* f;
int* p = &(f->*pm);
}
Note that this will only work if b isn't private in Foo, or alternative you could form the pointer to member in a member function or friend of Foo.
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