J
jacek.dziedzic
Hello!
Suppose I have a class base, with virtual methods and a virtual
destructor and a bunch of classes,
derived1, derived2, ... which publicly derive from base. I then have a
pointer
base* foo;
which a complicated code allocates as one of derived's and sets up.
Later on I have polymorphic
access to the underlying object via this base pointer foo.
At one point I need to create a deep copy of the object behind foo,
i.e. I have
base* foo_copy; // how do I deep-copy (*foo) into here?
This needs to copy a derived class, but, since I only have a base
pointer I do not know how
to go on about it, the first obstacle being the typename needed in the
new-expression which
would be used to allocate memory for foo_copy.
I tried new typeof(*foo), but, as far as I see, it is not
polymorphic and new'ed me a base class.
Sure, I could try dynamic_cast<>'ing foo to every possible derived
and see which one does
not return NULL (or is it bad_cast?) but that would involve a nasty
switch, wouldn't it?
So, the bottom line is -- how do I deep copy an object of one of the
derived classes, whilst
only having the base class pointer to the instance I want to copy?
Also, both the base classes and the derived classes do not have
(user-defined) copy ctors,
since they are almost-POD and I'm satisfied with the memberwise copy
construction. Is this
compiler-generated copy ctor safe to use here?
TIA,
- J.
Suppose I have a class base, with virtual methods and a virtual
destructor and a bunch of classes,
derived1, derived2, ... which publicly derive from base. I then have a
pointer
base* foo;
which a complicated code allocates as one of derived's and sets up.
Later on I have polymorphic
access to the underlying object via this base pointer foo.
At one point I need to create a deep copy of the object behind foo,
i.e. I have
base* foo_copy; // how do I deep-copy (*foo) into here?
This needs to copy a derived class, but, since I only have a base
pointer I do not know how
to go on about it, the first obstacle being the typename needed in the
new-expression which
would be used to allocate memory for foo_copy.
I tried new typeof(*foo), but, as far as I see, it is not
polymorphic and new'ed me a base class.
Sure, I could try dynamic_cast<>'ing foo to every possible derived
and see which one does
not return NULL (or is it bad_cast?) but that would involve a nasty
switch, wouldn't it?
So, the bottom line is -- how do I deep copy an object of one of the
derived classes, whilst
only having the base class pointer to the instance I want to copy?
Also, both the base classes and the derived classes do not have
(user-defined) copy ctors,
since they are almost-POD and I'm satisfied with the memberwise copy
construction. Is this
compiler-generated copy ctor safe to use here?
TIA,
- J.