← 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 the output shown in Expected Output. Do NOT write a main function.
Expected Output:
woof not a cat
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
Inheritance
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · 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.