I was reading on this page and it says
dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.
But dynamic_cast doesn't give a valid object when I do this:
struct A{};
struct B:A{};
void main(){
A a;
B b;
B* bPtr = (B*) 0x0000001;
A* aPtr = dynamic_cast<A*>(bPtr);
//Now aPtr is the memory address 0x00000001
}
Since the bPtr does not contain a valid A object, I would expect dynamic_cast to fail this cast so that aPtr would get NULL. But this is not happening? Which one is wrong, the compiler (g++ 4.5.7) or the above mentioned web page? Or am I missing something about what dynamic_cast is actually supposed to do?
Edit: Answer Summary
- In upcast, dynamic_cast does nothing. There is no guarantee of any sort.
- In downcast, dynamic_cast does not check for bad pointers. It assumes that the source pointer either is 0 or points to a valid source object. (the dynamic_cast operation can segfault during a downcast if it is given a bad pointer)
- Downcast through dynamic_cast requires at least one virtual member in the base class.
dynamic_cast<>
is typically intended. – iammilind