September 2018
Intermediate to advanced
606 pages
14h 32m
English
For the following example, we will require a C++ compiler compliant with the C++14 standard or later. The code for this recipe defines a polymorphic hierarchy of animals. We use std::unique_ptr for the base class in the hierarchy:
std::unique_ptr<Animal> cat = Cat("Simon");std::unique_ptr<Animal> dog = Dog("Marlowe);
Instead of explicitly using constructors for the various subtypes, we use an implementation of the factory method. The factory is implemented using C++11 variadic templates. It holds a map of creation functions for each object in the inheritance hierarchy:
typedef std::function<std::unique_ptr<Animal>(const std::string &)> CreateAnimal;
It dispatches them based on a preassigned tag, so that creation of objects ...
Read now
Unlock full access