Reputation: 575
I am reading Simple Event Handling. The author uses a simple struct for his events, but suggests:
A possible improvement here is to pass around a pointer to an Event class instead of a structure. The Event class could then contain any amount of information, and derived classes could be created for different types of events. I choose a simpler option, mainly because the scope of our project didn't require such a complex solution.
I implemented this as:
class Event
{
public:
typedef unsigned long EventType;
explicit Event(EventType type);
EventType getType() const;
private:
EventType mType;
};
class EventStr : public Event
{
public:
typedef unsigned long EventType;
EventStr(EventType type, std::string str);
std::string getString() const;
private:
std::string mString;
};
void EventDispatcher::sendEvent(const Event& event);
main()
{
Event e = EventStr(0x496bf752, "derived data");
SendEvent(e);
}
My thought was derived types could have their own unique data (in this example a string). However, I see this would require the use of dynamic_cast to access EventStr::getString when the event was being handled. On the flip-side I didn't use virtual functions, because I wanted the base class to be barebones and have the specific details in the derived class.
My understanding is dynamic_casts are typical of a poor design. That was my red flag. Is it possible to have a barebones base class and then add additional details to the derived class while still being able to pass the derived type around as a reference to the base class? If not what was the author suggesting?
Upvotes: 0
Views: 79
Reputation: 11831
If you have different event types, having a base event class and derived classes for the variant events is how object orientation is supposed to be used. Use function members defining pure virtuals for the different ways events react to their environment. The idea is precisely that so you can pass around objects as if they are of the base class.
You should look at a good C++ tutorial (yes, there are many "object oriented programming" tutorials/texts around, but the OOP languages are very different, so not all are of help). One I've seen is the one at cppreference, perhaps the wikibook. I'd bet Stroustrup's current The C++ Programming Language is very thorough and clear (judging from a much earlier edtion I own).
Upvotes: 1