Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is dynamic_cast<void*> useful? [duplicate]

Tags:

5.2.7/7 says something along the lines of:

If T is "pointer to cv void", the result is a pointer to the most derived class pointed to by x.

What is a good application of this synatx? When should dynamic_cast<void*> be used?

like image 497
David G Avatar asked Sep 01 '14 16:09

David G


People also ask

When would you use a static cast?

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.

Why do we use dynamic_cast?

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 .

What is the use of dynamic_cast in C++?

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.

What is the difference between dynamic_cast and static_cast?

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.


2 Answers

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.

like image 113
MSalters Avatar answered Sep 20 '22 20:09

MSalters


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); } 
like image 42
Paul Evans Avatar answered Sep 20 '22 20:09

Paul Evans