Gotcha #35: Unchecked Downcasting
Casting a base class pointer to a derived class pointer ("downcasting") may result in a bad address, as illustrated in the example below and in Figure 4-3. The delta arithmetic performed by the compiler on the casted pointer assumes that the base class address belongs to a base class part of the derived class:
class A { public: virtual ~A(); };
class B { public: virtual ~B(); };
class D : public A, public B {};
class E : public B {};
B *bp = getMeAB(); // get an object derived from B
D *dp = static_cast<D*>(bp); // safe???

The best approach is to design so that downcasting is unnecessary; systematic use of downcasts is often an indication of bad design. If a downcast really is required, it's often a good idea to use a dynamic_cast, which will perform a runtime check to ensure that the cast is correct:
if( D *dp = dynamic_cast<D *>(bp) ) {
// cast succeeded
}
else {
// cast failed
}
|