Casting polymorphic objects
Imagine that some programmer designed such an awful interface as follows (this is a good example of how interfaces should not be written):
struct object { virtual ~object() {} }; struct banana: public object { void eat() const {} virtual ~banana(){} }; struct penguin: public object { bool try_to_fly() const { return false; // penguins do not fly } virtual ~penguin(){} }; object* try_produce_banana();
Our task is to make a function that eats bananas, and throws exceptions if something different came instead of banana ( try_produce_banana()
may return nullptr
)so if we dereference a value returned by it without checking we are in danger of dereferencing a null pointer.
Getting started
Basic knowledge of C++ is required for this recipe.
How to do it...
So we need to write the following code:
void try_eat_banana_impl1() { const object* obj = try_produce_banana(); if (!obj) { throw std::bad_cast(); } ...