E
esuvs81
Hi, imagine I have a simple hierarchy with three classes - 'Base',
'Derived1', and Derived2. Base is an absrtact class and the two Derived
classes are concrete. Imagine at some point in my code I have a pointer
p1 of type 'Base' which actually points to an instance of one of the
derived objects. I would like to create a new pointer p2, also of type
'Base', which points to a copy of whatever the first one pointed to.
That is, I would like to copy the object at p1 without knowing it's
exact type. Is that possible?
My first attempt was something like:
Base* p2 = new Base(*p1);
But this didn't make sense because i was trying to instanciate an
abstract class. Maybe i actually need to know the exact type? Another
approach I thought of was to give each class a virtual function called
'copy' which would duplicate the object and return a pointer to the
duplicate. Does this make sense or is there a better way?
Thanks for any help,
David
'Derived1', and Derived2. Base is an absrtact class and the two Derived
classes are concrete. Imagine at some point in my code I have a pointer
p1 of type 'Base' which actually points to an instance of one of the
derived objects. I would like to create a new pointer p2, also of type
'Base', which points to a copy of whatever the first one pointed to.
That is, I would like to copy the object at p1 without knowing it's
exact type. Is that possible?
My first attempt was something like:
Base* p2 = new Base(*p1);
But this didn't make sense because i was trying to instanciate an
abstract class. Maybe i actually need to know the exact type? Another
approach I thought of was to give each class a virtual function called
'copy' which would duplicate the object and return a pointer to the
duplicate. Does this make sense or is there a better way?
Thanks for any help,
David