views:

267

answers:

2

I've been reading StackOverflow too much and started doubting all the code I've ever written, I keep thinking "Is that undefined behavour?" even in code that has been working for ages.

So my question - Is it safe and well defined behavour to cast a pointer to an object (In this case abstract interface classes) to a void* and then later on cast them back to the original class and call method using them?

I'm fully aware that the code that does this is probably awful. I wouldn't even consider writing it like this now (this is old code which I don't really want to change), so I'm not looking for a discussion of better ways to do this. I already know how to write it better if I ever did this again. But if it's actually broken to rely on this in C++ then I'll have to look at changing the code, if it's merely awful code then changing it won't be a priority.

I would have had no doubts about something this simple a year or two ago but as my understanding of C++ increases I actually find I have more and more worries about code being safe under the standards even if it works perfectly well. Perhaps reading too much stack overflow is a bad thing for productivity sometimes :P

+5  A: 

So my question - Is it safe and well defined behavour to cast a pointer to an object (In this case abstract interface classes) to a void* and then later on cast them back to the original class and call method using them?

Yes – as long as you cast back to the exact same type. Otherwise, base class pointer adjustments may destroy the value of the pointer.

In practice, this is (probably) only relevant when using multiple inheritance: pointers to a derived class may differ in their physical address from pointers to their base class.

Konrad Rudolph
+9  A: 
KennyTM
While this behaviour is of course unchanged in C++0x, I don't think it good practice to quote from an unaccepted draft standard to answer questions on the current state of the language.
anon
Thank you. I feel rather stupid asking such a basic question after 10 years of C++ programming, but the more I learn about c++ the more I doubt myself sometimes. Does anyone else feel that way? ... Hmm, just me then.
John Burton