C++ dynamic_cast Keyword
Example
Check which child class an Animal pointer points to:
class Animal {
public:
virtual void animalSound() {}
};
class Pig : public Animal {};
class Dog : public Animal {};
int main() {
Pig myPig;
Animal* myAnimal = &myPig;
Pig* pigPtr = dynamic_cast<Pig*>(myAnimal);
Dog* dogPtr = dynamic_cast<Dog*>(myAnimal);
cout << (pigPtr != nullptr) << "\n"; // 1, myAnimal points to a Pig
cout << (dogPtr != nullptr); // 0, myAnimal does not point to a Dog
return 0;
}
Definition and Usage
The dynamic_cast keyword converts a pointer or reference from a parent class to a child class. While the program runs, it checks that the object really is of that child class.
If the check fails, dynamic_cast returns nullptr for a pointer. For a reference, it throws an exception. In the example, myAnimal points to a Pig, so the conversion to Dog* fails.
dynamic_cast only works when the parent class has at least one virtual method.
Related Pages
Read more about polymorphism in our C++ Polymorphism Tutorial, and about virtual methods in our C++ Virtual Functions Tutorial.