views:

48

answers:

2

I am trying to make a function f that works like this:

StorageObject::addItem (const AbstractBase& base) {
    AbstractBase* storage = new Derived1(base);
}

However, I would like f to work with classes Derived2, Derived3 etc as well. Is there a way to get f to call the correct constructor depending on the specific subclass of AbstractBase passed to it, without using typecodes?

To put the question in context, I am using this function to initialize a list of objects in a class. While I could do something like

Derived1* temp = new Derived1();
storageobject.addItem(*temp);
delete temp;

I would prefer to do things like

storageobject.addItem(Derived1());

and have storageobject handle everything.

A: 
  • If you can use templates.
  • If you have not templates in language - use abstract factory pattern
Dewfy
+2  A: 

Why don't you implement a virtual copy method?

AbstractBase* storage = base.Copy()

By the way, this is quite C++ specific, because using C# it could be simply implemented by reflection.

Activiator.CreateInstance(temp.GetType(), temp);

Of course, there are some nice factory patterns around, but this really depends on the concrete problem you need to solve.

Stefan Steinegger
+1. The "Copy" method is the prototype pattern: http://en.wikipedia.org/wiki/Prototype_pattern
Tom Dalling
I'm using C++, and that seems to do the trick, thanks!
int3