Unable to access a body's userData

Hi all. I'm having a problem accessing the userData for a b2Body. I can feel I am really close to the solution, but can't quite get across the finish line. Here is what I have:

I have a base class called GameEntity from which I am deriving two subclasses:

Code:
class Ship: private GameEntity

and
Code:
class Meteorite: private GameEntity


Each of my GameEntities contain a pointer to their b2Body. And each body has the userData set to point to it's parent GameEntity, set when the body is created:

Code:
void Meteorite::CreateBody(GLfloat x, GLfloat y)
{
     // body creation code here...

     body->SetUserData(this);
}


Now the problem is that I can't find a way to access this data in my contact listener code. Here is what I have set up:

Code:

void Game::BeginContact(b2Contact *contact)
{
    b2Body *bodyA = contact->GetFixtureA()->GetBody();
    b2Body *bodyB = contact->GetFixtureB()->GetBody();

    const void* voidA = (bodyA->GetUserData());
    const void* voidB = (bodyB->GetUserData());
   
    const GameElement* objA = (GameElement*)(bodyA->GetUserData());
    const GameElement* objB = (GameElement*)(bodyB->GetUserData());

    // ... Collision detection code here ...
}


Something strange happens when I run this code. Let's say bodyA belongs to a Meteorite stored at 0x236b10 in memory. (I noted this memory address when the object was created). The object voidA will have the correct address, but as soon as I cast it to a GameElement, the address is changed to 0x236b0c. There always seems to be a 4 byte change in the address when I cast. This obviously breaks everything.

I would really appreciate any help you can give. What am I doing wrong, and what can I do?

I have searched around, but all the examples seem to be casting like I am.
I wonder if using public inheritance would fix it.
Thanks for the suggestion. But I have tried both public and private inheritance, and neither work.

Some reading around the internet suggests that this is simply the way casting works in C++. The act of casting an object to it's subtypet translates the address location to point to the right part of memory.

So my question is this:

How can I store an object as a void* and then retrieve it without modifying the address? I have tried the following:
  • Casting the object to a (void*) when I store it (to apply an inverse address translation).
  • using reinterpret_cast<GameElement*>

Do any c++ gurus have any pointers?

Original thread: https://box2d.org/forum/viewtopic.php?t=6835