โ Back to Inheritance
Question 451
Dynamic Cast to a Derived Type
Dynamic Cast to a Derived Type
dynamic_castsafely converts a base pointer to a derived pointer at RUNTIME: it returns a valid pointer if the object really is that type, ornullptrif it is not. The base must be polymorphic (have at least one virtual function). Create a polymorphic base classAnimal(give it a virtual destructor and a virtualstring kind() constreturning "animal"). CreateDog(overrideskind()-> "dog", addsstring bark() const-> "woof") andCat(overrideskind()-> "cat"). The runner has anAnimal*pointing to aDog.dynamic_cast<Dog*>succeeds (prints "woof");dynamic_cast<Cat*>returnsnullptr(prints "not a cat"). Output: woof not a cat Do NOT write a main function.
Expected Output:
woof not a cat
Topics:
Inheritance
Code Editor
1
Tab to indent ยท Ctrl+Enter to run ยท Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.