Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ offset of member variables?

Tags:

c++

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 ?
like image 847
anon Avatar asked Jan 19 '26 08:01

anon


1 Answers

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.

like image 86
CB Bailey Avatar answered Jan 20 '26 22:01

CB Bailey