Is there a safe and legal way to go from a pointer to a member of an object to a pointer to that same object?

Recommended Answers

All 3 Replies

What did you try that hasn't worked?

> Is there a safe and legal way to go from a pointer to a member of an object
> to a pointer to that same object?

No.

A pointer to a member is a pointer to a member of a class, not a pointer to a member of an object. When you dereference a pointer to a member of a class, you need you need to provide an object of that class with respect to which it is derefenced.

The object comes into picture only when the pointer to member is dereferenced; the same pointer to member can be dereferenced many times, each time with a different object.

Viyalan 121

A pointer to a member is really just an offset of that member to the start of the class.
Therefore assume that I have derefenced the pointer to member PTR_MBR using an instance I of the class C and obtain M.
Now, let's assume M is used later in the code and we don't have anymore knowledge of what instance it came from, only that it is a member of the class C obtained with PTR_MBR
Then couldn't we just say that the address of I is the adress of M minus the offset of the member in the class (which is PTR_MBR):
I = M - PTR_MBR !
It actually works when you do appropriate casting, but I suspect this is not much legal.
But is there a way to do this legally and without casting?

NOTE:
I am sure you will ask: What would you use it for?
There is a very useful situation which is the following.
Suppose you want to write a generic list iterator and you use in the implementation of the iterator the actual address of "next" which points to the address of the "next" of the next item, )and you also keep somewhere PTR_MBR of next for that item class).

Now, you want to obtain the item address itself from the address of "next", it would be great if you just go substract the PTR_MBR from the address of next.

Of course, the "normal" alternative is to have "next" point directly to the item (and then get the next "next" using the PTR_MBR) but that makes it less versatile because you might want to keep the pointer to the list as a simple isolated "next" without the rest of the item, something you could do with the previous approach but not with the "normal" alternative.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.