casting - a simple question

I have this simple question about casting... take a look at the code snippet below:

Base * pBase;
Derived * pDerived;

pBase=new Base(1);

//DOWNCAST:
pDerived = dynamic_cast<Derived*> (pBase); //Why did it NOT failed? Sure dynamic_cast supports "down-cast" but pBase is pointing to a "IN-complete" object.
//pDerived = (Derived*) pBase; //What's the difference between this sort of simple casting and dynamic_cast? I know that with simple casting, you can't down-cast. Does it mean that with up-cast, simple casting is just as good as dynamic_cast? I have a feeling that dynamic_cast will check at runtime if the object is complete/incomplete (simple casting don't do this) - and is thus safe. Is this the reason why we use dynamic_cast?

pDerived->m_nAge = 10; //Of course, this will crash.

Also, here's C4303 from MSDN:
"C-style cast from 'type1' to 'type2' is deprecated, use static_cast, __try_cast or dynamic_cast... C-style type casting or function-style casting is NOT SUPPORTED when using Managed Extensions for C++..."
>> I don't think it's NOT SUPPORTED - why the documentation states that it's not supported? I just did it in a C++ managed console application and it's just a warning - not error.

Thanks.
[1384 byte] By [nfung] at [2007-11-18 9:59:41]
# 1 Re: casting - a simple question
Originally posted by nfung
//DOWNCAST:
pDerived = dynamic_cast<Derived*> (pBase); //Why did it NOT failed? Sure dynamic_cast supports "down-cast" but pBase is pointing to a "IN-complete" object.
//pDerived = (Derived*) pBase; //What's the difference between this sort of simple casting and dynamic_cast? I know that with simple casting, you can't down-cast. Does it mean that with up-cast, simple casting is just as good as dynamic_cast? I have a feeling that dynamic_cast will check at runtime if the object is complete/incomplete (simple casting don't do this) - and is thus safe.

You get the compiler error because you cannot downcast pBase which is not an instance of Derived class. It should only work this way:

Base * pBase;
Derived * pDerived;

pBase=new Derived(1);
pDerived = dynamic_cast<Derived*> (pBase);
Kheun at 2007-11-9 0:25:17 >
# 2 Re: casting - a simple question
Take a look at this FAQ ( http://www.dev-archive.com/forum/showthread.php?s=&threadid=253032)...
Andreas Masur at 2007-11-9 0:26:15 >
# 3 Re: casting - a simple question
One reason it might not have failed is because some compilers (such as Microsoft's) require you to turn on RTTI for dynamic_cast to function properly. Since it looks like you are using the MS VC++ compiler, that is likely the source of the confusion. Note also that unlike reference casting, pointer casting with dynamic_cast will return null on failure (not throw an exception), so you need to check for NULL after the cast.
galathaea at 2007-11-9 0:27:22 >