How to populate a vector/list with all derived classes of a base class [closed]
I would like to get a vector/list of derived class pointers (one corresponding to each derived class from an abstract base class) given the base class name, for instance.
So to do exactly what you seems to want to do
#include <list>
class BaseObject { };
class Dinosaur : public BaseObject { };
class Hammer : public BaseObject { };
void
myFunction() {
std::list<BaseObject*> myList;
myList.push_back(new Dinosaur());
myList.push_back(new Hammer());
}
Note that the objects in the list won't free by themselves when the list will be destroyed. Either you have to do manually (Iterating over the list and calling delete), either look on something a bit complex if you are a C++ beginner, auto_ptr, and the magic world of the smart pointers ^^
You can't get a pointer to a class. A class is just a specification for an object. You only have something to point to once an object is created by instantiating the class.
If you have the following classes:
class FooBase {};
class DerivedFoo : public FooBase {};
class MoreDerivedFoo : public DerivedFoo {};
you can then create an object of type MoreDerivedFoo
and point to it using a pointer of any of those types.
MoreDerivedFoo mdf = new MoreDerivedFoo();
FooBase* p1 = &mdf;
DerivedFoo* p2 = &mdf;
MoreDerivedFoo* p3 = &mdf;
Obviously each of these pointers will contain the same memory address.
精彩评论