I
Imre
Hi
I know that offsetof is basically a C leftover, and only works for POD
types, not classes, so it is recommended that I use pointers to
members instead. However, I have a problem where I don't see how I
should use pointers to members.
Basically, I know how to get a member if I have an object and a
pointer-to-member (obj.*ptr instead of obj + offset), but I don't know
how to do the opposite: getting the object from a member address and a
pointer-to-member (that is, what to write instead of member - offset).
Here's what I need it for:
I have a class, for now let's just call it Outer. It has a member
variable, the type of which is a class called Inner. Inner has a
function F(). In F(), I need to have an Outer* pointer that points to
the Outer object that contains this Inner object.
class Inner
{
public:
virtual ~Inner() {}
void F();
};
class Outer
{
public:
Inner inner;
};
void Inner::F()
{
Outer* parent = ???;
}
Of course, a pointer to the parent Outer object could be passed to F()
as an argument, or as a constructor argument when creating
Outer::inner, but it seems to be unnecessary. In every Outer object,
the Inner object is at the same offset (this is guaranteed, isn't
it?), so we should be able to calculate the address of the the parent
Outer in Inner::F().
I can do this on compilers where offsetof is supported for classes as
well as PODs, but I'd like to know if there's a more portable
solution.
Thanks,
Imre
I know that offsetof is basically a C leftover, and only works for POD
types, not classes, so it is recommended that I use pointers to
members instead. However, I have a problem where I don't see how I
should use pointers to members.
Basically, I know how to get a member if I have an object and a
pointer-to-member (obj.*ptr instead of obj + offset), but I don't know
how to do the opposite: getting the object from a member address and a
pointer-to-member (that is, what to write instead of member - offset).
Here's what I need it for:
I have a class, for now let's just call it Outer. It has a member
variable, the type of which is a class called Inner. Inner has a
function F(). In F(), I need to have an Outer* pointer that points to
the Outer object that contains this Inner object.
class Inner
{
public:
virtual ~Inner() {}
void F();
};
class Outer
{
public:
Inner inner;
};
void Inner::F()
{
Outer* parent = ???;
}
Of course, a pointer to the parent Outer object could be passed to F()
as an argument, or as a constructor argument when creating
Outer::inner, but it seems to be unnecessary. In every Outer object,
the Inner object is at the same offset (this is guaranteed, isn't
it?), so we should be able to calculate the address of the the parent
Outer in Inner::F().
I can do this on compilers where offsetof is supported for classes as
well as PODs, but I'd like to know if there's a more portable
solution.
Thanks,
Imre