I have a tree containing various subtypes of the my base node class. I now want to traverse this tree and do something with the nodes depending on their type.
The most straightforward idea is to just define a method doSomething in my base node class, but this means that to add functionality I have to add a method to all existing node subtypes.
The first thing that comes to mind to solve this is the Visitor pattern. However, I want to be able to create new subtypes without having to change all existing visitors - I want the new subtypes to inherit the way they are handled from their base type.
I think using dynamic_cast should do the trick, but I understood that it is a costly operation, and it will be called a lot, so that is not a good solution. And many people say it is a sign of bad design, although I do not see the problem in this case.
At this moment I am using the first solution as I see foresee much more added types than functionality, but is there a better way to do this?
visitmethod in all the Visitor classes. See en.wikipedia.org/?title=Visitor_pattern#Diagram as an example. If you add a newDoorclass to theCarElementhierarchy, you will need to have avisit(Door door)method that needs implementing in all of the visitors.