From: Max H. <ma...@qu...> - 2001-01-21 20:10:19
|
At 20:56 Uhr +0100 21.01.2001, MIGUEL ANGEL BLANCH LARDIN wrote: >Hi, ( Uli ) > >I have been taking a look again to my C++ book on a free hour that I >have. >I have some questions: >STL containers don't use pointer, so if I have to insert a subclass, >what I do? as if I insert the subclass I am going to lose it. If you need to insert subclasses, you have to go with pointers rather than direct objects. E.g. use std::list<Object*> instead of std::list<Object>. Then you can insert Object*, MyObjectSubClass* etc. Drawback is that you have to delete the objects yourself on clear etc... However, it would be feasible to write a simple (template) subclass of std::list which would just do this all for you. This class would be used like AList<Object> but internally would use a std::list<Object*> (note the added *) E.g. template<class T> class AList : public std::list<T*> // note: { typedef std::list<T*> _base; AList() : _base() {} ... void clear() { for(_base::const_iterator X = begin(); X != end(); ++X) delete *X; _base::clear(); } ... }; In fact, it might be better to use a HAS-A relation here than an IS-A relation... Max -- ----------------------------------------------- Max Horn C/C++ Developer email: <mailto:ma...@qu...> phone: (+49) 6151-494890 |