开发者

How to populate a vector/list with all derived classes of a base class [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question 开发者_Go百科so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜