3.2 Down casting

Down casting refers to a cast from a superlcass type to a subclass type. This can be rather dangerous. Down casting also support reference and pointer casting. To understand why this is dangerous, observe the following code (based on the definitions of class A and class B from the previous section):

A myA;
B *pMyB = static_cast<B*>(&myA);

The compiler actually lets this slide! In other words, the pointer pMyB is now really pointing to an object of class A, but we can use it as if it points to a class B object. This code will lead to problems!



Copyright © 2006-10-12 by Tak Auyeung