What is the advantage of using dynamic_cast instead of conventional polymorphism?

前端 未结 5 1882
青春惊慌失措
青春惊慌失措 2020-12-18 04:19

We can use Polymorphism (inheritance + virtual functions) in order to generalize different types under a common base-type, and then refer to different objects as if they wer

5条回答
  •  青春惊慌失措
    2020-12-18 05:11

    I can't think of any case where it's not possible to use virtual functions (other than such things as boost:any and similar "lost the original type" work).

    However, I have found myself using dynamic_cast a few times in the Pascal compiler I'm currently writing in C++. Mostly because it's a "better" solution than adding a dozen virtual functions to the baseclass, that are ONLY used in one or two places when you already (should) know what type the object is. Currently, out of roughly 4300 lines of code, there are 6 instances of dynamic_cast - one of which can probably be "fixed" by actually storing the type as the derived type rather than the base-type.

    In a couple of places, I use things like ArrayDecl* a = dynamic_cast(type); to determine that type is indeed an array declaration, and not someone using an non-array type as a base, when accessing an index (and I also need a to access the array type information later). Again, adding all the virtual functions to the base TypeDecl class would give lots of functions that mostly return nothing useful (e.g. NULL), and aren't called except when you already know that the class is (or at least should be) one of the derived types. For example, getting to know the range/size of an array is useless for types that aren't arrays.

提交回复
热议问题