dynamic_cast question

Started by
11 comments, last by Helter Skelter 18 years, 9 months ago
Quote:Original post by Nypyren
If I had to implement dynamic_cast in a compiler, I'd just CMP the object's vtable pointer to the compiler-known vtable pointer for the type in question, return the object if they match or NULL otherwise.


Unfortunately that won't work in the following situation.

class A { public: virtual ~A(); };class B : public A {};class C : public B { virtual void next(); };B *Downcast(A* src){    return dynamic_cast<B*>(src);}void go(){    C *c = new C;    B *b = Downcast(C);}


C will have a virtual table different than A and B. In the above example if(B::vtable == src->vtable) will return false and the dynamic cast will fail.
Advertisement
Quote:Original post by Helter Skelter
Quote:Original post by Nypyren
If I had to implement dynamic_cast in a compiler, I'd just CMP the object's vtable pointer to the compiler-known vtable pointer for the type in question, return the object if they match or NULL otherwise.


Unfortunately that won't work in the following situation.


It won't work with any downcast, and will work with a very select few upcasts. Example:

struct A { virtual void make_me_polymorphic() {} };struct B : A {};struct C : B {};int main () {    C exampleC;    C * c = &exampleC;    B * b = dynamic_cast< B * >( c ); //whoops, *c == typeof(C) not typeof(B)    A * a = b; //this works, dynamic_cast should in a similar situation too.    a = &exampleC; //*a == typeof(C)    b = dynamic_cast< B * >( a ); //whoops, *a == typeof(C) not typeof(B)    c = dynamic_cast< C * >( a ); //why should this work but not the above line?}


Throw in multiple and virtual inheritence and things can get pretty complicated :-). The actual address pointed to can end up changing!!!
Quote:Original post by MaulingMonkey
Throw in multiple and virtual inheritence and things can get pretty complicated :-). The actual address pointed to can end up changing!!!


Not to mention how pointers to virtual member functions are handled based on their location in the vtable.

I wish it was as easy as checking the vtable pointer...would make things much more interesting [smile]

This topic is closed to new replies.

Advertisement