int3
int3

Reputation: 13201

Pattern for initializing unknown subclass

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.

Upvotes: 0

Views: 111

Answers (2)

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

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.

Upvotes: 2

Dewfy
Dewfy

Reputation: 23644

  • If you can use templates.
  • If you have not templates in language - use abstract factory pattern

Upvotes: 0

Related Questions