Hi all,
I have two C++ structures. Both structures include a parameterless
constructor that initializes the structure members. These two structures
define different ways of looking at the same data; one structure exposes the
data as an array of bytes, the other exposes the bytes as individual
structure members. However, because of the constructors, I can't create a
higher-level struct that unions the two structures together. (The
structures in a union can not have a user-supplied default constructor.)
So, here's my question: If I have an instance of one structure type, is
there a way to tell C++ to treat it as though it is an instance of the other
structure type without having to create an overloaded "=" operator that
moves bytes in memory? The reinterpret_cast operator would seem to be just
what I want, but it refuses to cast one type to a totally unrelated type.
TIA - Bob
Bob Altman - 28 Nov 2007 20:31 GMT
Never mind... I left a magic "&" off of the reinterpret_cast syntax that I
used in my code. I found an excellent writeup on the general subject of
"type punning" (yes, that's "pun" as in "play on words") here:
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VSADD.v10.en/
dndeepc/html/deep06012000.htm
- Bob
> Hi all,
>
[quoted text clipped - 14 lines]
>
> TIA - Bob
Ben Voigt [C++ MVP] - 28 Nov 2007 20:40 GMT
> Never mind... I left a magic "&" off of the reinterpret_cast syntax that
> I used in my code. I found an excellent writeup on the general subject of
> "type punning" (yes, that's "pun" as in "play on words") here:
I still think you should use the union (see my other post), as the layout of
a non-POD type isn't necessarily sequential (that's why they can't be used
inside a union).
> ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VSADD.v10.en/
> dndeepc/html/deep06012000.htm
[quoted text clipped - 19 lines]
>>
>> TIA - Bob
Ben Voigt [C++ MVP] - 28 Nov 2007 20:32 GMT
> Hi all,
>
[quoted text clipped - 12 lines]
> be just what I want, but it refuses to cast one type to a totally
> unrelated type.
(1) reinterpret_cast the address as a pointer to the other type
(2) use a union, and put the initialization in the constructor for the union
itself