static_cast downcast trap
#include <iostream>
class A{
public:
virtual void Print(){
printf("A\n");
}
};
class B : public A {
public:
void Print() override {
printf("B\n");
}
};
class C : public A {
public:
void Print() override {
printf("C\n");
}
int* myPtr;
};
using namespace std;
int main()
{
A* b = new B();
A* c = new C();
// this is bad. static_cast will compile so you think you have a variable of type C
if (C* fakeC = static_cast<C*>(b))
{
// but you don't, so dereferencing myPtr will result in trying to reference garbage memory and crash
if (*(fakeC->myPtr) == 1)
printf("1");
}
printf("we'll never get here because the above dereference of myptr will crash");
// In this scenario, if we don't know what actual type b is,
// we should use dynamic_cast which WILL fail the cast and thus not fall into the if statement
if (C* realC = dynamic_cast<C*>(b))
bc->Print();
return 0;
}
Last updated