Casting/dereferencing member variable pointer from void*, is this safe?

Posted by Damien on Stack Overflow See other posts from Stack Overflow or by Damien
Published on 2010-06-11T03:42:11Z Indexed on 2010/06/11 3:53 UTC
Read the original article Hit count: 148

Filed under:

Hi all,

I had a problem while hacking a bigger project so I made a simpel test case. If I'm not omitting something, my test code works fine, but maybe it works accidentally so I wanted to show it to you and ask if there are any pitfalls in this approach.

I have an OutObj which has a member variable (pointer) InObj. InObj has a member function. I send the address of this member variable object (InObj) to a callback function as void*. The type of this object never changes so inside the callback I recast to its original type and call the aFunc member function in it. In this exampel it works as expected, but in the project I'm working on it doesn't. So I might be omitting something or maybe there is a pitfall here and this works accidentally. Any comments? Thanks a lot in advance.

(The problem I have in my original code is that InObj.data is garbage).

#include <stdio.h>

class InObj
{
public:
 int data;
 InObj(int argData);
 void aFunc()
 {
  printf("Inside aFunc! data is: %d\n", data);
 };
};

InObj::InObj(int argData)
{
 data = argData;
}

class OutObj
{
public:
 InObj* objPtr;
 OutObj(int data);
 ~OutObj();
};

OutObj::OutObj(int data)
{
 objPtr = new InObj(data);
}

OutObj::~OutObj()
{
 delete objPtr;
}

void callback(void* context)
{
 ((InObj*)context)->aFunc();
}

int main ()
{
 OutObj a(42);
 callback((void*)a.objPtr);
}

© Stack Overflow or respective owner

Related posts about c++