Mistake: assuming a base-class pointer can safely be treated as a derived-class pointer. dynamic_cast checks the conversion at run time: an incompatible pointer cast returns null, while an incompatible reference cast throws an exception. Check pointer results before using them; consider whether polymorphic behavior can avoid the cast. section 5.6
Listing 5.13 Using C++-style casts more reservedly and responsibly
struct B {
virtual int compute() { return 0; }
};
struct D : public B {
int n;
D() : n(42) {}
int compute() { return n; }
};
int main() {
const char msg[] = "Hello, world";
char* p = const_cast<char*>(msg); #1
*(p+1) = 'a';
std::cout << msg << '\n';
int n = 0x2A2A2A2A;
char* c = reinterpret_cast<char*>(&n); #2
for (int i = 0; i < sizeof(int); ++i)
std::cout << *(c+i);
std::cout << '\n';
// std::cout << static_cast<double*>(msg) << '\n'; #3
std::cout << static_cast<double>(n) << '\n'; #4
B* b = new B();
D* d = dynamic_cast<D*>(b); #5
if (d)
std::cout << d->compute() << '\n';
else
std::cout << "incompatible downcast\n";
return 0;
}
The example downcasts a pointer to a B object—not a D object—and checks for null before calling a derived-class method. section 5.6

