Alex Rivera | Logout

Are there practical uses for dynamic-casting to void pointer?

Asked 2011-11-14T15:22:20.720
78

In C++, the T q = dynamic_cast<T>(p); construction performs a runtime cast of a pointer p to some other pointer type T that must appear in the inheritance hierarchy of the dynamic type of *p in order to succeed. That is all fine and well.

However, it is also possible to perform dynamic_cast<void*>(p), which will simply return a pointer to the "most derived object" (see 5.2.7::7 in C++11). I understand that this feature probably comes out for free in the implementation of the dynamic cast, but is it useful in practice? After all, its return type is at best void*, so what good is this?

Edit
Report

1 Answer

4

Casting pointers to void* has its importance since way back in C days. Most suitable place is inside the memory manager of Operating System. It has to store all the pointer and the object of what you create. By storing it in void* they generalize it to store any object on to the memory manager data structure which could be heap/B+Tree or simple arraylist.

For simplicity take example of creating a list of generic items(List contains items of completely different classes). That would be possible only using void*.

standard says that dynamic_cast should return null for illegal type casting and standard also guarantees that any pointer should be able to type cast it to void* and back from it with only exception of function pointers.

Normal application level practical usage is very less for void* typecasting but it is used extensively in low level/embedded systems.

Normally you would want to use reinterpret_cast for low level stuff, like in 8086 it is used to offset pointer of same base to get the address but not restricted to this.

Edit: Standard says that you can convert any pointer to void* even with dynamic_cast<> but it no where states that you can not convert the void* back to the object.

For most usage, its a one way street but there are some unavoidable usage.

It just says that dynamic_cast<> needs type information for converting it back to the requested type.

There are many API's that require you to pass void* to some object eg. java/Jni Code passes the object as void*.
Without type info you cannot do the casting.If you are confident enough that type requested is correct you can ask compiler to do the dynmaic_cast<> with a trick.

Look at this code:

answered 2011-11-16T19:14:37.973

Your Answer