Archived

This topic is now archived and is closed to further replies.

Structural

Inheritance and copying to vectors

Recommended Posts

Here''s the problem... I have this vector that stores menu items. Things like buttons and windows are derived from a generic class MenuItem. Specific to a button, is a character array, text. When I do a push_back on my vector, adding a button, the character array text isn''t copied somehow. My question is, can I store derived classes in a vector of the base class without any problems? Or should I only store the pointer in the vector?

Share this post


Link to post
Share on other sites
I think vector<baseClass> would make an array of the BaseClass, then copy to and from it when you need it. So there wouldn''t be any room to store the extra info for the derived class. So use a pointer, and virtual functions.

Share this post


Link to post
Share on other sites
Use a vector<baseClass*>.
A vector<baseClass> only allocates space for a baseClass object; so only the baseClass part of the object is copied into the vector when pushing back.
Of course, when using pointers, you should use new and delete, otherwise your objects on the stack will be destroyed and the pointers in the vector will point to nothing.


---
Just trying to be helpful.

Sebastian Beschke
Just some student from Germany
http://mitglied.lycos.de/xplosiff

Share this post


Link to post
Share on other sites
or use/make a smartpointer(a pointer that deletes itself) class and use a array of smartpointers. it's really a very nice thing to have. (btw. std::auto_ptr is not goot, and can't be used in vectors, because there can only be one copy of the same pointer at the time. if you make one your self you should mnae one with a reference counter, that deletes the object when there are no more references)

My Site


[edited by - Quasar3D on October 5, 2003 5:50:29 PM]

Share this post


Link to post
Share on other sites