Re: Collections of derived objects
In article <4ba31cbc$0$2858$ba620e4c@news.skynet.be>,
olivier.scalbert@algosyn.com says...
Hello,
Let's say I have a base class Event and some sub classes EventType1,
EventType2, ...
1)
I would like to have a collection (vector or list for example) of a mix
of EventType1, EventType2, ...
I think I have to create a vector<Event*> and starts playing with "new".
And of course, I will forget the "delete" !
Are there any other options, to keep the code clean ?
You can make many higherarchies that you have control over value types
with some work. It involves the use of the handle/body idiom:
// event.h
struct event
{
// NVI
typedef ? event_type_id;
event_type_id event_type() const { return pimpl->event_type(); }
//...
event(event_type_id id);
struct impl
{
virtual event_type_id event_type() const = 0;
// ...
};
private:
std::auto_ptr<impl> pimpl;
};
// event.cpp
struct x_event : event::impl
{
event_type_id event_type() const { return ??; }
};
event::impl * impl_factory(event_type_id id)
{
event::impl * = new ?? discovery;
}
event::event(event_type_id id) : pimpl(impl_factory(id)) {}
-------------------------
Issue with this design: subclasses MUST all have the exact same requests
to implement. For example, mouse_event could not have extra or
different functionality from keyboard_event. It could only implement
that functionality with differing behavior. You're probably better off
with the pointer solution but I figured more knowledge can't hurt.
2)
I would like to transform (serialize in string or something else) these
events (contained into a collection). As I will have different
transformations, I do not want to put the serialization code inside the
events, to not pollute them. How can I do that, in a clean way ? Visitor
pattern or something like that?
Visitor is debatably clean. I have found it quite useful. You could
also get "Modern C++ Design" and read the chapter on multimethods.