Can anybody give me a real world example of a case when dynamic_cast is needed and can’t be worked around at all? Examples I can think of can generally be worked around with double dispatch.
If the constraint is too strong, an example where dynamic_cast is generally the way to go would also be nice.
I’d like to see real examples instead of “it’s normally used to cast between types up and down a type tree”.
Double dispatch requires that the types that are interacting have intimate knowledge of each other’s innards, as it requires that one class call methods on the other class.
dynamic_castworks when you cannot modify the innards of a class, or do not wish to break encapsulation of the classes in question.That is, double dispatch is invasive on the classes involved, while
dynamic_castworks without knowledge of the cast in the classes.You can also use
dynamic_castif you don’t know the target method overload which will be invoked. For an example, see this question I posted yesterday.Finally, double dispatch does not come without it’s own headaches