Re: copy derived structure, is it legal c++ code?
FFMG schrieb:
I am trying to copy some variables from a struct to a derived struct.
If I have something like,
...
struct STRUCTA
{
int numA;
long numB;
float numC;
}
struct STRUCTB public STRUCTA
{
int numD;
}
[There are many syntactical errors up to now.]
...
STRUCTA structA = {0,1,2};
STRUCTB structB;
memcpy( &structB, &structA, sizeof( STRUCTA) );
...
//
Is the above code legal to copy the structure from structA to structB
It is not valid. It is undefined bahaviour.
STRUCTB is no longer a POD type because of the inheritance.
However, as long as neither STRUCTA or STRUCTB has virtual Methods or
things like that it usually works. But think what happens if STRUCTB is
defined as:
struct STRUCTB : public STRUCTC, public STRUCTA
{
int numD;
}
Your code will most likely fail badly.
And as far as I know there is no guarantee that the A part of B is in
the front of B. This is implementation defined.
But there is no need for the memcpy in your case at all since C++
supports slicing. B has also the properties of A, so you can assign the
A slice independantly. But this is no implicit conversion.
You must either explicitely address the A part by doing a cast
static_cast<STRUCTA&>structB = structA;
or you must call the assignment operator of STRUCTA explicitely
structB.STRUCTA::operator=(structA);
I would prefer the first since I am unsure wether the second one is a
language extension of gcc.
Marcel