CJCoding With Joseph

Dynamic Cast to a Derived Type

dynamic_cast safely converts a base pointer to a derived pointer at RUNTIME: it returns a valid pointer if the object really is that type, or nullptr if it is not. The base must be polymorphic (have at least one virtual function).

Create a polymorphic base class Animal (give it a virtual destructor and a virtual string kind() const returning "animal").
Create Dog (overrides kind() -> "dog", adds string bark() const -> "woof") and Cat (overrides kind() -> "cat").

The runner has an Animal* pointing to a Dog. dynamic_cast<Dog*> succeeds (prints "woof"); dynamic_cast<Cat*> returns nullptr (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.