Re: Casting from void*
On 2011-06-28 16:13, Noah Roberts wrote:
Correct me if I'm wrong:
A static cast to void* is guaranteed to create a pointer that points at
the beginning of the object.
There's no such guarantee for static_cast<void*>; on the other hand,
dynamic_cast<void*>(v) does give a pointer to the most derived object
pointed to by v.
Thus:
struct X { ... };
struct Y { ... };
struct Z : X,Y { ... };
Y * ptr = new Z;
void * vptr = ptr;
Now ptr != vptr.
ptr is Y*, and vptr is void*. Comparing them causes ptr to be implicitly
converted to void*, and vptr is exactly what you get from it. Therefore,
ptr == vptr.
Instead vptr == static_cast<X*>(ptr).
You cannot use static_cast to convert Y* to X*, because X and Y are not
in an inheritance relationship (i.e. one being derived from the other).
So, that statement doesn't make sense ("doesn't compile").
You need dynamic_cast for cross-casting.
It seems that you have something like this in mind:
struct X { ... };
struct Y { ... };
struct Z : X, Y { ... };
Y* py = new Z;
void* pv = dynamic_cast<void*>(py);
assert(pv != py);
assert(pv == dynamic_cast<X*>(py));
You need dynamic_cast, and the classes should be polymorphic.
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]