multiple inheritance: unexpected result after cast from void * to 2nd base class

Repeat ten times - the only thing you can safely do with a reinterpret_cast pointer is reinterpret_cast it back to the same pointer type it came from. The same applies with conversions to void*: you must convert back to the original type.

So, if you cast a DecoratedSquare* to void*, you must cast it back to DecoratedSquare*. Not Decorated*, not Square*, not Shape*. Some of them might work on your machine, but this is a combination of good luck and implementation-specific behaviour. It usually works with single-inheritance, because there's no obvious reason to implement object pointers in a way which would stop it working, but this is not guaranteed, and it can't work in general for multiple inheritance.

You say that your code accesses "arbitrary types, including primitive types" via a void*. There's nothing wrong with this - presumably whoever receives the data knows to treat it as a DecoratedSquare* and not as, say, int*.

If whoever receives it only knows to treat it as a base class, such as Decorated*, then whoever converts it to void* should static_cast it to the base class first, then to void*:

void *decorated_vp = static_cast<Decorated*>(ds);

Now when you cast decorated_vp back to Decorated*, you'll get the result of static_cast<Decorated*>(ds), which is what you need.


It's not a compiler bug - it's what reinterpret_cast does. The DecoratedSquare object will be laid out in memory something like this:

Square
Decorated
DecoratedSquare specific stuff

Converting a pointer to this to void* will give the address of the start of this data, with no knowledge of what type is there. reinterpret_cast<Decorated*> will take that address and interpret whatever is there as a Decorated - but the actual memory contents are the Square. This is wrong, so you get undefined behaviour.

You should get the correct results if you reinterpret_cast to the correct dynamic type (that is DecoratedSquare), then convert to the base class.