-
Would you use dynamic cast in a frequently run method? Does it have
a large overhead? -
What exactly IS the pointer returned by dynamic_cast. A pointer to the same address?
a pointer to a different instance? I lack this understanding. More in specific –
There’s an assignment I wish to make to a pointer of a father type only if in runtime it
turns out to be a pointer to a son type. Solutions?
Thank you.
dynamic_casthelps you check the validity while performing downcasting.It returns a NULL or throws an exception(
std::bad_castfor References)if the pointer or the reference cannot be safely downcasted.Would you use dynamic cast in a frequently run method? Does it have a large overhead?
dynamic_castdoes use some additionalRTTI(Run Time Type Information)for determining the validity of cast. So there is an overhead for sure. Typically, a pointer totypeinfoof thetypewill be added to thevirtual table. I say typically, because virtual mechanism itself is compiler implementation dependant detail(may vary for different compilers).You will have to profile your code using some good profiling tools to determine if calling
dynamic_castrepeatedly reduces the performance of your code.What exactly IS the pointer returned by
dynamic_cast. A pointer to the same address? a pointer to a different instance?It is easier to understand when instead of analyzing downcasting with
dynamic_castwe analyze upcasting. Given a typebaseand another typederivedthat inherits frombase, thederivedtype will contain a subobject of typebase. When a pointer to aderivedobject is upcasted to a pointer tobase, the result of the operation will be the address of thebasesubobject insidederived. Performing adynamic_castreverts that operation, and returns a pointer to thederivedobject that contains abasesubobject in the address passed as argument (static_castdoes the same, but it will apply the possible offset without actually checking the runtime type).In the simplest case, with single (non-virtual) inheritance the
derivedsubobject will be alignedbase, but in the event of multiple inheritance, that will not be the case:The program will print
true,false. Note that you have to explicitly cast one of the pointers tovoid*if you want to compare them, or else the compiler will perform an implicit upcast the downcasted pointer.