Hi all.
Problem: I have a pretty big structure with POD variables, and I need to copy around some fields, but not others. Too lazy to write down a member-by-member copy function.
Solution: move the copy-able fields to the base, assign the base. Like this:
struct A
{
int a, b, c;
};
struct B : public A
{
int d, e, f;
};
//And copy:
B x, y;
(A&)x = y; //copies the part of B that is A
Now, this is dirty, I know. I had a live, livid discussion with co-workers re: this code, my competence, and my moral character. Yet the hardest specific charge I heard was "d, e, f are not initialized in the copy". Yes I know; that was the intent. Of course I initialize them elsewhere.
Another charge was "unsafe typecast". But this is a guaranteed-safe typecast to the base class! Is's almost like
((A*)&x)->operator=(b);
but less verbose. The derivation is public; so treating B as A is fair game. There's no undefined behavior, as far as I can see.
So, I'm appealing to the collective wizdom of SO. This is an invitation to criticism. Have a go at it, people.
EDIT: the final line of the snippet can be expanded into less offensive code in more than one way. For example:
void Copy(A& to, const A& from)
{
to = from;
}
B x, y;
Copy(x, y);
Functionally the same. Or like this:
x.A::operator=(y);
EDIT2: there's no maintenance programmer but me. It's from a hobby project. So stop pitying that poor soul.