Allow me to give some background. I have an abstract class, Foo.
class Foo {
public:
virtual void bar() = 0;
}
I have two classes that inherit from this class.
class FooOne : public Foo {
public:
void bar();
}
and
class FooTwo : public Foo {
public:
void bar();
}
Now in a completely different class, I want to create an array in a function that can hold instances of one of these two classes. The problem that I’m running into is that I cannot create an array with a dynamic type like this, can I? I’m used to Objective-C where I can create an object of type id.
Ideally, this is what I was looking for (pseudocode):
void someFunction(FooType type) {
class aClass = (type == FooTypeOne ? FooOne : FooTwo);
vector<aClass> container;
// Do something with the container.
}
Note: I cannot use C++11 in this project.
You could use smart pointer in STL container:
As you are using C++03, shared_ptr is available under
std::tr1Note:
You need to add virtual destructor to
FooOtherwise, you get undefined behavior if you delete an object of a derived type through a pointer to the base.