سؤال

Why static_cast<>() (also known as downcast) doesn't casts types run-time while dynamic_cast<>() (also known as upcast) does? Both are used to advance through class hierarchy. What could be so different between them that it is necessary for dynamic_cast<>() to cast types run-time?

هل كانت مفيدة؟

المحلول

Both are usually used for downcasting (from a base to a derived class); upcasting is always safe, so doesn't need an explicit cast. As noted in the comments, both are equivalent (and equivalent to an implicit conversion) if you use them for upcasting.

For downcasting, static_cast is faster but potentially dangerous, since it doesn't perform a runtime check and gives undefined behaviour if the conversion is not valid. It also works with non-polymorphic types, while dynamic_cast requires the run-time type information that's only available from polymorphic types.

Your introductory book should cover this in detail.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top