The dynamic_cast
operator in C++ is used for safe downcasting of polymorphic types. It ensures that the cast is valid at runtime by checking the actual object type before allowing the cast to proceed. If the cast is not valid, it returns nullptr
for pointers or throws an exception for references. This makes it a safer option compared to traditional casts.
dynamic_cast
SafelyTo use dynamic_cast
safely, you should always check the result of the cast operation. The following example demonstrates how to use dynamic_cast
properly:
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
public:
void display() {
std::cout << "Derived class" << std::endl;
}
};
void safeDynamicCast(Base* basePtr) {
Derived* derivedPtr = dynamic_cast(basePtr);
if (derivedPtr) {
derivedPtr->display(); // Safe to use derivedPtr
} else {
std::cout << "Invalid cast" << std::endl;
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?