In my program I have a base Object class and a vector. I have an operation that I want to perform on each Object*, however the operation is dependent on the Object*’s most derived class. Therefore, I use the visitor pattern. However, I’ve found that the visitor pattern leads to a high amount of coupling; whenever I add a new Object derived class, I must change the base Visitor and every class that derives from Visitor.
Is there an easier way to perform an operation on a list of objects based on their run time type that does not lead to such high coupling?
I’m going to read between the lines and guess that your most derived objects have member functions that are unique to them and don’t exist in any of the other derived objects, which is why you don’t want to add them to the base class.
You can use
dynamic_castto see if a pointer belongs to the most derived class, then call the function if it does.