dynamic_cast
- C++ course
- Intermediate
- Lesson 39/116
- 5 min
Learn safe downcasting with dynamic_cast.
dynamic_cast
dynamic_cast performs a safe downcast in polymorphic classes. It converts a base pointer to a derived type; if the conversion is invalid it returns nullptr.
Example: Animal* a = new Dog();. If you know a is really a Dog, write Dog* d = dynamic_cast<Dog*>(a);. If d is not nullptr, call d->fetch(). For dynamic_cast to work, the class must have at least one virtual method; otherwise it gives a compile error.
RTTI and nullptr check
dynamic_cast uses runtime type information (RTTI). It checks the actual type of the pointer through the vtable, so it only works on polymorphic classes.
If the types are incompatible, it throws std::bad_cast for references and returns nullptr for pointers. Using a pointer and checking with if (d) is safer. dynamic_cast carries a small performance cost but prevents crashes from bad downcasts.
Practice Downcast to Dog with dynamic_cast
Define an Animal class with virtual void speak() and virtual ~Animal() {}. A Dog class inherits, adds speak() override and an extra void fetch() with body std::cout << "Ball";. In main write Animal* a = new Dog();, Dog* d = dynamic_cast<Dog*>(a);, if (d) d->fetch(); and delete a;.
Starter code
#include <iostream>
// Define Animal and Dog classes here
int main() {
// Create a Dog via Animal*, downcast with dynamic_cast and call fetch
return 0;
}Sample solution
#include <iostream>
class Animal {
public:
virtual void speak() {}
virtual ~Animal() {}
};
class Dog : public Animal {
public:
void speak() override {}
void fetch() { std::cout << "Ball"; }
};
int main() {
Animal* a = new Dog();
Dog* d = dynamic_cast<Dog*>(a);
if (d) d->fetch();
delete a;
return 0;
}Expected output
Ball
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is dynamic_cast used?
Dog* d = dynamic_cast<Dog*>(a);- For safe downcasting Correct answer
- For static variables
- For array access
- For type promotion
Explanation: dynamic_cast safely converts a base pointer to a derived type.
2 Match each piece to its role
| Term | Meaning |
|---|---|
dynamic_cast |
Safe downcast |
Dog* |
Target type |
virtual ~Animal |
Required polymorphic base |
if (d) |
Null pointer check |
3 Complete the dynamic_cast call
Dog* d = dynamic_cast<____>(a);
Dog* d = dynamic_cast<Dog*>(a);
Explanation: The target type is the derived class pointer: Dog*.