Failed runtime cast from a base class reference to a derived class reference using dynamic_cast.
In C++, using dynamic_cast on reference types throws a std::bad_cast exception if the dynamic type of the object doesn't match the target derived type. Unlike pointers, which return nullptr on failure, dynamic_cast with references cannot return null, so it throws std::bad_cast.
Attempting to dynamically cast a base reference parameter to a derived reference type when the referenced object is not actually an instance of that derived type.
1#include <iostream>2#include <typeinfo>3 4class Base { public: virtual ~Base() {} };5class DerivedA : public Base {};6class DerivedB : public Base {};7 8void process(Base& b) {9 // Bug: Throws std::bad_cast if b is DerivedB10 DerivedA& a = dynamic_cast<DerivedA&>(b);11}12 13int main() {14 DerivedB db;15 process(db); // Triggers std::bad_cast16 return 0;17}1#include <iostream>2#include <typeinfo>3 4class Base { public: virtual ~Base() {} };5class DerivedA : public Base {};6class DerivedB : public Base {};7 8void process(Base& b) {9 // Fix 1: Catch std::bad_cast exception10 try {11 DerivedA& a = dynamic_cast<DerivedA&>(b);12 std::cout << "Successfully cast to DerivedA!\n";13 } catch (const std::bad_cast& e) {14 std::cerr << "Cast failed: " << e.what() << "\n";15 }16 17 // Fix 2: Or use pointers if cast is optional (returns nullptr on failure)18 if (DerivedA* aPtr = dynamic_cast<DerivedA*>(&b)) {19 std::cout << "Successfully cast to pointer DerivedA!\n";20 }21}22 23int main() {24 DerivedB db;25 process(db);26 return 0;27}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
Since b refers to an object of type DerivedB, casting it to DerivedA& fails. C++ references must refer to valid instances, so instead of returning a null reference (which is impossible), the dynamic_cast operator throws a std::bad_cast exception.