Ok, I seem to be requiring forward casting from base to derived and I think it might be a design problem so I will explain what I’m doing and you can tell me what I need change.
XML file defines a bunch of objects that are similar. They share the same base class. The main function is defined in the base class DoWork() and it’s virtual.
My program loads XML file and creates the derived classes and assigns them to a vector of type base class.
Everything is great the program works. I can iterate through the vector and call DoWork();
Now, I’ve added a GUI layer so you can modify the objects and write back a XML file. So, now my GUI code has access to the vector of base class pointers. But, this is no good because I need the info from the derived class so I can write out the XML file. Is the only solution to this dynamic casting? Could I have changed the design somehow? I know casting from base to derived is frowned upon.
EDIT: My GUI needs to display information that the derived class has as well. Just having a serialize class is not enough.
There are two different approaches that you can take here. The first one is providing a virtual method that generates the XML corresponding to the element.
The second approach is providing a visitor interface: basically you define a virtual method that accepts a
visitortype. The visitor type will be called with the current object at each level of the hierarchy, generating a type of double dispatch mechanism. This way the virtual dispatch will resolve to the most derived object, that will call upon the visitor object to serialize itself.The first approach is simpler, while the second has the advantage of a looser coupling between each object in the hierarchy and the actual serialization format. That is, you can produce different visitors that can serialize to different formats without having to modify code in your current hierarchy.