I’m working on a small framework in C++ to use in some of my projects, to statically link against as a utility library of sorts. I guess you could compare it to a more domain-specific to my personal needs, and simpler library like juce. This is as much a learning and experience exercise as anything else, so I’d like to take the time to do things properly and understand the techniques I apply. I’m currently working in linux, but aiming for the code to be portable, so this will allow me to write any platform specific code to an interface.
At the moment I’m working on a basic messaging system, which I would like to allow for messages that include objects of various types. My initial thought was like so:
class Message {
virtual std::string type;
};
class DataMessage : Message {
std::vector<std::string> *data;
};
My question is, what is the best way to identify that a Message is a DataMessage, and either cast it to its actual type, or access the data it contains?
I can use a string for the type like above, but that doesn’t guarantee each subclass will actually have a unique type id. Also, I wonder if the overhead of string processing would be slower than an alternative (could I extend an enum, for example?).
As for accessing the data, if I can cast the Message to its proper type, this is not an issue. Otherwise, I could add a virtual function to the base class as either an accessor (but then how do I have it use a different return type to the one specified in the base class? What if the class doesn’t need any additional data?), or as a worker function that acts on the data (but I would rather have it just as a data passing mechanism between classes, versus a callback style framework).
Any suggestions, alternatives or links are much appreciated. Discussion of different approaches would be awesome!
Thanks in advance guys.
You can use
DataMessage* pDataMessage = dynamic_cast<DataMessage*>(pMessage). ThepDataMessagewill be valid only ifpMessageis aDataMessageobject. Otherwise it will beNULL.