I have an abstract class Base, with derived classes Derived1, Derived2, etc. I don't know how many there are. So, I have declared an object of Derived like so: Base* der1 = new Derived1(/* constructor details */);
That gets passed to a function, which modified the data contained by this pointer. However, I need to keep the data from the object, which means that I need to copy the data somehow. The problem is, this copying needs to be done within the function, due to the requirements of the program. I do not know what type the object is, This function will need to reset this data potentially hundreds of times, so I can't just provide lots of objects, as either the function will run out of objects to call or I will run out of space in memory.
How would I create a copy of this, so that I would be modifying a temporary object that could be deleted and I would keep the data that I started with?
I had already considered this, but because of the number of possible derived classes I had rejected this idea, and the fact that (from what I know) casting in that way can be too slow (and this function is already a bottleneck for program execution). However, as I do more research, I think that this will be probably be the way I have to go.
To externalise the the state of an object without violating its encapsulation, and later restore the object to a previous state, use the memento pattern. http://sourcemaking.com/design_patterns/memento