Type coercion

B

Bob Altman

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
 
B

Bob Altman

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
 
B

Ben Voigt [C++ MVP]

Bob Altman said:
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.

(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
 
B

Ben Voigt [C++ MVP]

Bob Altman said:
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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top