My code was acting wonky and i was able to mini reproduce it with the code below. (codepad link)
From http://www.cppreference.com/wiki/keywords/dynamic_cast
If you attempt to cast to a pointer
type, and that type is not an actual
type of the argument object, then the
result of the cast will be NULL.
From my understanding this_test should be null. It isnt. How do i check if that dummy ptr is actually a ptr to a dummy object?
#include <ios>
struct Dummy{ virtual void dummyfn(){} };
int main(){
Dummy* this_test = dynamic_cast<Dummy*>((Dummy*)0x123);
//assert(this_test==0);
cout << std::hex << this_test<<endl;
return 0;
}
output:
0x123
The issue is that
dynamic_castexpects either:Here you can only offer it garbage, so it is useless, and not the cast you want.
If you are getting a
void*, then you can usereinterpret_cast(better than a C-cast, because more visible) to cast it into another type:Note: the presence or absence of virtual methods goes unnoticed here
EDIT: if you can modify the objects being passed…
Then try to use a common base class:
And define the following helpers:
The former is extremely important because of the possible pointer adjustment (which will probably only occur in the case of Multiple Inheritance).
Note: it’s possible to use a
fast_casthere if you don’t use virtual inheritance or other RTTI stuffIf this is not possible the following solutions are possible, but they are going to feel hacky I fear.
Since
dynamic_castis not going to work properly here, you have to actually come up with your own type checking mechanism.One method could be to use a “repository” in which you register the
void*pointers you get, and the associatedtype_infoobject.If this is not possible, then you could hack the C++ object model to your advantage. If you know that the object has at least one virtual method, then it necessarily has a virtual pointer on all compilers I know (VS, gcc, clang), and this pointer is the first 4/8 bytes of the object.
Note: both solutions suffer from the same shortcoming, they will only work if you precise the exact type (well, you could get away with it as long as two types share the same virtual table, which happens if a derived class does not override any virtual method, including the destructor).
This is far from the power of a true
dynamic_cast.