Pointer-to-member

M

mk

In C++ one can get an absolute address of data member, having a
pointer-to-member and a pointer to class object:

struct A
{
int m;
};

void f(A *a)
{
int A::*b = &A::m;
int *c = &(a->*b); // address-wise: c = a + b
}

Unfortunetly it seems that inverse operation, that is getting a
pointer to class object having pointer-to-member and absolute pointer
to member is impossible in a standard C++ program. This is a well
defined, simple operation that could be used this way:

void f(int *c)
{
int A::*b = &A::m;
A *a = /* what to put here? */ // address-wise: a = c - b;
}

Is there anything standard-compliant that I can put in place of
comment?

cheers,
Marcin Kalicinski
 
V

Victor Bazarov

mk said:
In C++ one can get an absolute address of data member, having a
pointer-to-member and a pointer to class object:

struct A
{
int m;
};

void f(A *a)
{
int A::*b = &A::m;
int *c = &(a->*b); // address-wise: c = a + b

You could do it in one operation:

int *c = &(a->m);

there is no need for "pointer to member" dance.
}

Unfortunetly it seems that inverse operation, that is getting a
pointer to class object having pointer-to-member and absolute pointer
to member is impossible in a standard C++ program. This is a well
defined, simple operation that could be used this way:

void f(int *c)
{
int A::*b = &A::m;
A *a = /* what to put here? */ // address-wise: a = c - b;
}

Is there anything standard-compliant that I can put in place of
comment?

For PODs you could use a combination of 'reinterpret_cast' and 'offsetof'.

However, while the former operation is *always* defined (any A has
a member named 'm'), the reverse is not defined for all pointers to int.

What if I do

int a = 42;
f(&a);

? Suddenly you're trying to figure out what object the integer belongs to
and there is no such thing...

So, why would you want to do that, anyway?

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,662
Latest member
sxarexu

Latest Threads

Top