The dangers of casting pointers

There are various dangers when casting pointers to different types but as a general rule, casting to a void pointer and back to the original pointer is considered safe. Unfortunately, this is not always the case as this little quiz demonstrates.

Question: What is the result of this code?

struct Foo
{
   void func(){}
};

typedef void (Foo::*func_t)();

int main()
{
   func_t fp1 = func_t(&Foo::func);
   void * p = (void*) fp1;
   func_t fp2 = (func_t) p;

   Foo foo;
   (foo.*fp2)();
}

Answer: The result is undefined.

Why?

A pointer to a member is not a pointer to an object or a pointer to a function and the rules for conversions of such pointers do not apply to pointers to members. In particular, a pointer to a member cannot be converted to a void pointer.

The same is also true for function pointers, which cannot be safely cast to a void pointer.

More info: C++ FAQ Lite (member function pointers)
More info: C++ FAQ Lite (function pointers)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s