dynamic_cast help
Object* a = new Object(40, 'a');
delete a;
void* b = new Object(40, 'b');
a=dynamic_cast<Object*>b;//why can't i do this?
delete a;
Thank you!
to do a dynamic cast from b to a
a has to be inherited from b and b has to have a virtual destructor
a has to be inherited from b and b has to have a virtual destructor
Quote:Original post by Hermes
Object* a = new Object(40, 'a');
delete a;
void* b = new Object(40, 'b');
a=dynamic_cast<Object*>b;//why can't i do this?
delete a;
Thank you!
Firstly,
a=dynamic_cast<Object*>b
should be
a=dynamic_cast<Object*>(b)
Secondly, the compiler can't determine what type the object is because your providing it with a void*, which provides absolutely no information to the compiler about the type of the object. The compiler at least needs to know what class heirachy the object is part of. A better example of dynamic_cast would be
ObjectBase* b = new Object(40,'b');Object* a = dynamic_cast<Object*>(b);
Quote:Original post by Anonymous Poster
to do a dynamic cast from b to a
a has to be inherited from b and b has to have a virtual destructor
A virtual destructor isn't necessary for dynamic_cast, but it's a good idea none-the-less.
Quote:Original post by Hermes
Object* a = new Object(40, 'a');
delete a;
void* b = new Object(40, 'b');
a=dynamic_cast<Object*>b;//why can't i do this?
delete a;
i can't see why you really must need to do this but if you really do then dynamic_cast is not the one for you, dynamic_cast is used to navigate type hierarchies of related types, you wont a cast that lets you cast between un-related types which is reinterpret_cast e.g
Object* a = new Object(40, 'a');delete a;void* b = new Object(40, 'b');a= reinterpret_cast<Object*>(b);delete a;
Quote:Original post by joanusdmentiaQuote:Original post by Anonymous Poster
to do a dynamic cast from b to a
a has to be inherited from b and b has to have a virtual destructor
A virtual destructor isn't necessary for dynamic_cast, but it's a good idea none-the-less.
From what I've heard, lots of implementations uses the v-table to check on types and when using dynamic_cast, so you'll need at least one virtual function.. and as a general rule, when at least one function is virtual, the destructor should be virtual, too.
Quote:Original post by Jolle
From what I've heard, lots of implementations uses the v-table to check on types and when using dynamic_cast, so you'll need at least one virtual function.
That could very well be true, it does sound familiar.
Quote:and as a general rule, when at least one function is virtual, the destructor should be virtual, too.
Yep, hence me mentioning that the virtual destructor was a good idea anyway. I was really just nit-picking [smile]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement