<p>We often hear/read that one should avoid dynamic casting. I was wondering what would be 'good use' examples of it, according to you?</p>

<p>Edit:</p>

<p>Yes, I'm aware of <a href="https://stackoverflow.com/questions/28002/regular-cast-vs-staticcast-vs-dynamiccast">that other thread</a>: it is indeed when reading one of the first answers there that I asked my question!</p>

[{'answer_id': 28096, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': '<p>My current toy project uses dynamic_cast twice; once to work around the lack of multiple dispatch in C++ (it\'s a visitor-style system that could use multiple dispatch instead of the dynamic_casts), and once to special-case a specific subtype.</p>\n\n<p>Both of these are acceptable, in my view, though the former at least stems from a language deficit.  I think this may be a common situation, in fact; most dynamic_casts (and a great many "design patterns" in general) are workarounds for specific language flaws rather than something that aim for.</p>\n'}, {'answer_id': 104096, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 0, 'selected': False, 'text': "<p>It can be used for a bit of run-time type-safety when exposing handles to objects though a C interface.  Have all the exposed classes inherit from a common base class.  When accepting a handle to a function, first cast to the base class, then dynamic cast to the class you're expecting.  If they passed in a non-sensical handle, you'll get an exception when the run-time can't find the rtti.  If they passed in a valid handle of the wrong type, you get a NULL pointer and can throw your own exception.  If they passed in the correct pointer, you're good to go.\nThis isn't fool-proof, but it is certainly better at catching mistaken calls to the libraries than a straight reinterpret cast from a handle, and waiting until some data gets mysteriously corrupted when you pass the wrong handle in.</p>\n"}, {'answer_id': 117185, 'author': 'rlerallut', 'author_id': 20055, 'author_profile': 'https://Stackoverflow.com/users/20055', 'pm_score': 1, 'selected': False, 'text': "<p>Here's something I do often, it's not pretty, but it's simple and useful.</p>\n\n<p>I often work with template containers that implement an interface,\nimagine something like</p>\n\n<pre><code>template&lt;class T&gt;\nclass MyVector : public ContainerInterface\n...\n</code></pre>\n\n<p>Where ContainerInterface has basic useful stuff, but that's all. If I want a specific algorithm on vectors of integers without exposing my template implementation, it is useful to accept the interface objects and dynamic_cast it down to MyVector in the implementation. Example:</p>\n\n<pre><code>// function prototype (public API, in the header file)\nvoid ProcessVector( ContainerInterface&amp; vecIfce );\n\n// function implementation (private, in the .cpp file)\nvoid ProcessVector( ContainerInterface&amp; vecIfce)\n{\n    MyVector&lt;int&gt;&amp; vecInt = dynamic_cast&lt;MyVector&lt;int&gt; &gt;(vecIfce); \n    // the cast throws bad_cast in case of error but you could use a\n    // more complex method to choose which low-level implementation\n    // to use, basically rolling by hand your own polymorphism.\n\n    // Process a vector of integers\n    ...\n}\n</code></pre>\n\n<p>I could add a Process() method to the ContainerInterface that would be polymorphically resolved, it would be a nicer OOP method, but I sometimes prefer to do it this way. When you have simple containers, a lot of algorithms and you want to keep your implementation hidden, dynamic_cast offers an easy and ugly solution.</p>\n\n<p>You could also look at double-dispatch techniques.</p>\n\n<p>HTH</p>\n"}, {'answer_id': 303260, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Well it would really be nice with extension methods in C#.</p>\n\n<p>For example let\'s say I have a list of objects and I want to get a list of all ids from them.  I can step through them all and pull them out but I would like to segment out that code for reuse.</p>\n\n<p>so something like</p>\n\n<pre><code>List&lt;myObject&gt; myObjectList = getMyObjects();\n\nList&lt;string&gt; ids = myObjectList.PropertyList("id");\n</code></pre>\n\n<p>would be cool except on the extension method you won\'t know the type that is coming in.</p>\n\n<p>So </p>\n\n<pre><code>public static List&lt;string&gt; PropertyList(this object objList, string propName) {\n    var genList = (objList.GetType())objList;\n}\n</code></pre>\n\n<p>would be awesome.</p>\n'}, {'answer_id': 303312, 'author': 'Mark Ransom', 'author_id': 5987, 'author_profile': 'https://Stackoverflow.com/users/5987', 'pm_score': 3, 'selected': False, 'text': '<p>This recent thread gives an example of where it comes in handy. There is a base Shape class and classes Circle and Rectangle derived from it. In testing for equality, it is obvious that a Circle cannot be equal to a Rectangle and it would be a disaster to try to compare them. While iterating through a collection of pointers to Shapes, dynamic_cast does double duty, telling you if the shapes are comparable and giving you the proper objects to do the comparison on.</p>\n\n<p><a href="https://stackoverflow.com/questions/301959/vector-iterator-not-dereferencable">Vector iterator not dereferencable</a></p>\n'}, {'answer_id': 22732741, 'author': 'Zsolt Szatmari', 'author_id': 1725165, 'author_profile': 'https://Stackoverflow.com/users/1725165', 'pm_score': 0, 'selected': False, 'text': "<p>It is very useful, however, most of the times it is <em>too</em> useful: if for getting the job done the easiest way is to do a dynamic_cast, it's more often than not a symptom of bad OO design, what in turn might lead to trouble in the future in unforeseen ways.</p>\n"}]
['https://Stackoverflow.com/questions/28080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2638/']