5.2.7/7 says something along the lines of:
If
T
is "pointer tocv void
", the result is a pointer to the most derived class pointed to byx
.
What is a good application of this synatx? When should dynamic_cast<void*>
be used?
This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc.
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 .
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 inheritance when you cast from base class to derived class.
Static casting is done by the compiler: it treats the result as the target type, no matter what. You do this when you're absolutely sure about the argument being of the target type. Dynamic casting is done at runtime, and thus requires runtime type information.
One common reason is to figure out whether two interfaces IA*
and IB*
are in fact pointers to the same underlying object. If you need that, use the cast.
IIRC, it's even possible in case of Multiple Inheritance with a repeated non-virtual base to have two IA*
pointers which compare unequal, yet point to the same object - because they point to two different IA
subobjects.
When you have something like:
template<typename X, typename Y> bool operator==(const X* px, const Y* py) { return dynamic_cast<void*>(px) == dynamic_cast<void*>(py); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With