How it works...

The factory pattern provides an object that allocates resources with a means to change the types that the object allocates. To better understand how this pattern works and why it is so useful, let's look at the following example:

class know_it_all{public:    auto ask_question(const char *question)    {        (void) question;        return answer("The answer is: 42");    }};

We start, as shown in the preceding code, with a class called know_it_all that provides an answer when asked a question. In this particular case, no matter what question is asked, it always returns the same answer. The answer is defined as the following:

class answer{    std::string m_answer;public:    answer(std::string str) :        m_answer{std::move(str)}    { }};

As shown in the preceding, ...

Get Advanced C++ Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.