Safe type casting in C++ is provided by the casting operators: static_cast, dynamic_cast, const_cast, reinterpret_cast.
nullptr for pointers or throw an exception for references.When to use:
dynamic_cast with virtual bases. For converting between primitive/compatible types — static_cast.Example:
struct Base { virtual ~Base() {} }; struct Derived : Base { void foo() {} }; void test_cast(Base* base) { // Safe downcasting to derived class Derived* d = dynamic_cast<Derived*>(base); if (d) { d->foo(); } }
Question: Can you cast a base class object to a derived class using static_cast if the object is not actually an instance of the derived class?
Answer: Yes, static_cast will compile, but the behavior will be undefined if the object is not actually an instance of the derived class. Only dynamic_cast guarantees the safety of such a cast. Using static_cast for downcasting is acceptable only if you are sure of the actual type of the object.
Story
In a large embedded system, casts between the parent and child class were done using static_cast. In some cases, this led to crashes when attempting to access non-existent fields — the program tried to interpret memory of a different type.
Story
When developing a plugin architecture, programmers used reinterpret_cast to cast pointers between different types, which led to reading garbage and crashes at runtime, especially when attempting dynamic casting through DLLs.
Story
In a general corporate framework, virtual destructors in the base class were forgotten, making it impossible to work correctly with dynamic_cast and leading to memory leaks and corruption when deleting an object through a base class pointer.