Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real world example of dynamic_cast in C++

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".

like image 403
Russell Avatar asked Jul 01 '11 20:07

Russell


People also ask

What is dynamic_cast used for?

The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .

When should I use dynamic_cast?

dynamic_cast −This cast is used for handling polymorphism. You only need to use it when you're casting to a derived class. This is exclusively to be used in inheritence when you cast from base class to derived class.

Which exception is thrown by dynamic_cast?

The bad_cast exception is thrown by the dynamic_cast operator as the result of a failed cast to a reference type.

Does dynamic_cast use RTTI?

For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b' (of type `class B*') to type `class D*' (source type is not polymorphic) ” because there is no virtual function in the base class B.


1 Answers

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_cast works 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_cast works without knowledge of the cast in the classes.

You can also use dynamic_cast if 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

The base class Shape must know about all the derived classes, resulting in circular dependencies. If you derive a new class from Shape (say Triangle), you must update the interface of Shape and the interface/implementation of all the other derived classes. In some cases this is not even an option: you may not have the source code for Shape, or not be willing or permitted to modify it.

like image 177
Billy ONeal Avatar answered Sep 18 '22 18:09

Billy ONeal