Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic_cast of void *

Tags:

c++

I need to use dynamic cast void*

void *target = (MYClass*)target;//I am storing initially(to implment delegate mechanism)
....
delegateClass *delegate = dynamic_cast<delegateClass*>(target);

It is giving error cannot convert void*, I cannot use below code... since it is a delegate mechanism

delegateClass *delegate = dynamic_cast<delegateClass*>(((MYClass*))target);

How to get the type of target and implement... If i use typeid() i can get the name of the class but how to use typeid in the above equation instead of (((MYClass*))target).

like image 371
Chandan Shetty SP Avatar asked Dec 07 '22 20:12

Chandan Shetty SP


2 Answers

You cannot use dynamic cast unless the original type of the variable had a vtable (ie, had virtual functions). This is because dynamic_cast requires run-time type information, which is recorded in the vtable; if the vtable is missing, the compiler doesn't know what type the object is.

You should declare a base class with a virtual destructor, and use pointers to this base class rather than void *.

like image 60
bdonlan Avatar answered Dec 18 '22 16:12

bdonlan


If you must pass the object as a void * then you should use

delegateClass *delegate = static_cast<delegateClass*>(((MYClass*))target);

as there is no class relationship between the void *target and delegateClass. Here you are saying that you know that target _is_a_ delegateClass.

However this idiom is usually used for passing code through standard C interfaces and back.

like image 22
DanS Avatar answered Dec 18 '22 16:12

DanS