U
Ulrich Hobelmann
Hi, slowly transitioning from C to C++, I decided to remodel a
struct/union (i.e. type identifier as first field, union of variant
types) as a class + subclasses. Switching functions are replaced by
virtual functions. So far so good.
Now what I used to do is have a struct, set its type and union member,
and return a pointer. I.e. I initialized the struct appropriately and
returned a reference. Now I'd like to do that in C++ (right now I
construct a new subclass with "new" and delete it after every call,
because the instance is only needed very shortly anyway; seems ugly to me).
I tried to define a union that contains all subclasses (that I will ever
use) of the base class, but C++ complains that it can't have objects
with constructors or destructors inside a union.
Is there any way to have a static piece of storage, and to return
references/objects(by value) or pointers to this piece of storage, while
also initializing it (i.e. myunion.objectB = ObjectB(); return
myunion.objecTB; or something like that)? In C I didn't need malloc()
in this case; I don't see why I should need new() now.
struct/union (i.e. type identifier as first field, union of variant
types) as a class + subclasses. Switching functions are replaced by
virtual functions. So far so good.
Now what I used to do is have a struct, set its type and union member,
and return a pointer. I.e. I initialized the struct appropriately and
returned a reference. Now I'd like to do that in C++ (right now I
construct a new subclass with "new" and delete it after every call,
because the instance is only needed very shortly anyway; seems ugly to me).
I tried to define a union that contains all subclasses (that I will ever
use) of the base class, but C++ complains that it can't have objects
with constructors or destructors inside a union.
Is there any way to have a static piece of storage, and to return
references/objects(by value) or pointers to this piece of storage, while
also initializing it (i.e. myunion.objectB = ObjectB(); return
myunion.objecTB; or something like that)? In C I didn't need malloc()
in this case; I don't see why I should need new() now.