Factory Design Pattern in Modern C++
Tags: cpp, programming, design, tutorial
Published: 2020-06-29 04:40:33

<!-- wp:paragraph -->
<p>In software engineering, Creational Design Patterns deal with object creation mechanisms, i.e. try to create objects in a manner suitable to the situation. In addition to this basic or ordinary form of object creation could result in design problems or added complexity to the design. Factory Design Pattern in C++ helps to mitigate this issue by <strong><em>creating objects using separate methods or polymorphic classes</em></strong>.</p>
<!-- /wp:paragraph -->

> /!\\\: This article has been originally published on my [blog](http://www.vishalchovatiya.com/factory-design-pattern-in-modern-cpp/). If you are interested in receiving my latest articles, [please sign up to my newsletter](http://eepurl.com/gDNybv).

By the way, If you haven't check out my other articles on Creational Design Patterns, then here is the list:

1.  **[Factory](http://www.vishalchovatiya.com/factory-design-pattern-in-modern-cpp/)**
2.  **[Builder](http://www.vishalchovatiya.com/builder-design-pattern-in-modern-cpp/)**
3.  **[Prototype](http://www.vishalchovatiya.com/prototype-design-pattern-in-modern-cpp/)**
4.  **[Singleton](http://www.vishalchovatiya.com/singleton-design-pattern-in-modern-cpp/)**

The code snippets you see throughout this series of articles are simplified not sophisticated. So you often see me not using keywords like `override`, `final`, `public`(while inheritance) just to make code compact & consumable(most of the time) in single standard screen size. I also prefer `struct` instead of `class` just to save line by not writing "`public:`" sometimes and also miss [virtual destructor](http://www.vishalchovatiya.com/part-3-all-about-virtual-keyword-in-c-how-virtual-destructor-works/), constructor, [copy constructor](http://www.vishalchovatiya.com/all-about-copy-constructor-in-cpp-with-example/), prefix `std::`, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using Jargons.

***Note:***

-   If you stumbled here directly, then I would suggest you go through [What is design pattern?](http://www.vishalchovatiya.com/what-is-design-pattern/) first, even if it is trivial. I believe it will encourage you to explore more on this topic.
-   All of this code you encounter in this series of articles are compiled using C++20(though I have used [Modern C++](http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/) features up to C++17 in most cases). So if you don't have access to the latest compiler you can use <https://wandbox.org/> which has preinstalled boost library as well.

<!-- wp:heading -->
<h2>Intent</h2>
<!-- /wp:heading -->

> **For the creation of wholesale objects unlike builder(which creates piecewise).**

<!-- wp:heading -->
<h2>Motivation</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Let say you have a <code>Point</code> class having <code>x</code> &amp; <code>y</code> as co-ordinates which can be Cartesian or Polar coordinate as below:</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
```C++
struct Point {
	Point(float x, float y){ /*...*/ } 		// Cartesian co-ordinates

	// Not OK: Cannot overload with same type of arguments
	// Point(float a, float b){ /*...*/ } 	 // Polar co-ordinates

	// ... Implementation
};
```
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>This isn't possible as you might know you can not create two constructors with the same type of arguments.</li><li>Other way around is:</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
```C++
enum class PointType{ cartesian, polar };

class Point {
    Point(float a, float b, PointTypetype = PointType::cartesian) {
        if (type == PointType::cartesian) {
            x = a; b = y;
        }
        else {
            x = a * cos(b);
            y = a * sin(b);
        }
    }
};
```
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>But this isn't a sophisticated way of doing this. Rather we should delegate separate instantiation to separate methods.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Factory Design Pattern Examples in C++</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>So as you can guess. We are going to mitigating constructor limitation by moving the initialization process from constructor to other structure. And we gonna be using the Factory Method for that.</li><li>And just as the name suggests it uses the method or member function to initialize the object.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Factory Method</h3>
<!-- /wp:heading -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
```C++
enum class PointType { cartesian, polar };

class Point {
    float       m_x;
    float       m_y;
    PointType   m_type;

    // Private constructor, so that object can't be created directly
    Point(const float x, const float y, PointType t) : m_x{x}, m_y{y}, m_type{t} { }
public:
    friend ostream& operator<<(ostream& os, const Point& obj) {
        return os << "x: " << obj.m_x << " y: " << obj.m_y;
    }
    static Point NewCartesian(float x, float y) { 
        return { x, y, PointType::cartesian }; 
    }
    static Point NewPolar(float a, float b) { 
        return { a*cos(b), a*sin(b), PointType::polar }; 
    }
};

int main() {
    // Point p{ 1,2 };  // will not work
    auto p = Point::NewPolar(5, M_PI_4);
    cout << p << endl;  // x: 3.53553 y: 3.53553
    return EXIT_SUCCESS;
}
```
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>As you can observe from the implementation. It actually disallows the use of constructor &amp; forcing users to use static methods instead. And this is the essence of the <strong><em>Factory Method i.e. private constructor &amp; static method</em></strong>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Classical Factory Design Pattern </h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>If you have dedicated code for construction then while not we move it to a dedicated class. And Just to do separation of concerns i.e. <a href="http://www.vishalchovatiya.com/single-responsibility-principle-in-cpp-solid-as-a-rock/" target="_blank" rel="noreferrer noopener"><span style="color:#170cec" class="color">Single Responsibility Principle</span></a> from SOLID design principles.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
```C++
class Point {
    // ... as it is from above
    friend class PointFactory;
};

class PointFactory {
public:
    static Point NewCartesian(float x, float y) {
        return { x, y };
    }
    static Point NewPolar(float r, float theta) {
        return { r*cos(theta), r*sin(theta) };
    }
};
```
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Mind that this is not the abstract factory this is a concrete factory. </li><li>Making the <code>PointFactory</code> friend class of <code>Point</code> we have violated the <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/open-closed-principle-in-cpp-solid-as-a-rock/" target="_blank"><span style="color:#170cec" class="color">Open-Closed Principle</span></a>(OCP). As friend keyword itself contrary to OCP.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Inner Factory </h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>There is a critical thing we missed in our Factory that there is no strong link between <code>PointFactory</code> &amp; <code>Point</code> which confuses user to use <code>Point</code> just by seeing everything is <code>private</code>.</li><li>So rather than designing a factory outside the class. We can simply put it in the class which encourage users to use Factory. </li><li>Thus, we also serve the second problem which is breaking the <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/open-closed-principle-in-cpp-solid-as-a-rock/" target="_blank"><span style="color:#170cec" class="color">Open-Closed Principle</span></a>. And this will be somewhat more intuitive for the user to use Factory.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
```C++
class Point {
    float   m_x;
    float   m_y;

    Point(float x, float y) : m_x(x), m_y(y) {}
public:
    struct Factory {
        static Point NewCartesian(float x, float y) { return { x,y }; }
        static Point NewPolar(float r, float theta) { return{ r*cos(theta), r*sin(theta) }; }
    };
};

int main() {
    auto p = Point::Factory::NewCartesian(2, 3);
    return EXIT_SUCCESS;
}
```
<!-- /wp:enlighter/codeblock -->

<!-- wp:heading {"level":3} -->
<h3>Abstract Factory</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Why do we need an Abstract Factory?</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>C++ has the support of polymorphic object destruction using it’s base class’s&nbsp;<a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/part-3-all-about-virtual-keyword-in-c-how-virtual-destructor-works/" target="_blank"><span style="color:#0d00a3" class="color">virtual destructor</span></a>. Similarly, equivalent support for creation &amp; copying of objects is missing as С++ doesn’t support <a rel="noreferrer noopener" aria-label="virtual constructor (opens in a new tab)" href="http://www.vishalchovatiya.com/7-advanced-cpp-concepts-idiom-examples-you-should-know/" target="_blank"><span style="color:#0029a3" class="color">virtual constructor</span></a> &amp;&nbsp;<a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/all-about-copy-constructor-in-cpp-with-example/" target="_blank"><span style="color:#0015a3" class="color">copy constructors</span></a>.</li><li>Moreover, you can’t create an object unless you know its static type, because the compiler must know the amount of space it needs to allocate. For the same reason, copy of an object also requires its type to known at compile-time.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
```C++
struct Point {
    virtual ~Point(){ cout<<"~Point\n"; }
};

struct Point2D : Point {
    ~Point2D(){ cout<<"~Point2D\n"; }
};

struct Point3D : Point {
    ~Point3D(){ cout<<"~Point3D\n"; }
};

void who_am_i(Point *who) { // Not sure whether Point2D would be passed here or Point3D
    // How to `create` the object of same type i.e. pointed by who ?
    // How to `copy` object of same type i.e. pointed by who ?
    delete who; // you can delete object pointed by who, thanks to virtual destructor
}
```
<!-- /wp:enlighter/codeblock -->

<!-- wp:heading {"level":4} -->
<h4>Example of Abstract Factory Design Pattern</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The Abstract Factory is useful in a situation that requires the creation of many different types of objects, all derived from a common base type. </li><li>The Abstract Factory defines a method for creating the objects, which <a href="http://www.vishalchovatiya.com/memory-layout-of-cpp-object/" target="_blank" rel="noreferrer noopener" aria-label="subclasses (opens in a new tab)"><span style="color:#0007a3" class="color">subclasses</span></a> can then override to specify the derived type that will be created. Thus, at run time, the appropriate Abstract Factory Method will be called depending upon the type of object referenced/pointed &amp; return a base class pointer to a new instance of that object. </li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
```C++
struct Point {
    virtual ~Point() = default;
    virtual unique_ptr<Point> create() = 0;
    virtual unique_ptr<Point> clone()    = 0;
};

struct Point2D : Point {
    unique_ptr<Point> create() { return make_unique<Point2D>(); }
    unique_ptr<Point> clone() { return make_unique<Point2D>(*this); }
};

struct Point3D : Point {
    unique_ptr<Point> create() { return make_unique<Point3D>(); }
    unique_ptr<Point> clone() { return make_unique<Point3D>(*this); }
};

void who_am_i(Point *who) {
    auto new_who       = who->create(); // `create` the object of same type i.e. pointed by who ?
    auto duplicate_who = who->clone();    // `copy` the object of same type i.e. pointed by who ?
    delete who;
}
```
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>As shown above, we have leveraged polymorphic methods by delegating the act of creation &amp; copying the object to the derived class through the use of pure virtual methods.</li><li>Above code is not only implement <code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="http://www.vishalchovatiya.com/7-advanced-cpp-concepts-idiom-examples-you-should-know/#Virtual-Constructor" target="_blank"><span style="color:#001aa3" class="color">virtual constructor</span></a></code>(i.e.&nbsp;<code>create()</code>) but also implements <a rel="noreferrer noopener" aria-label="virtual&nbsp;copy constructor&nbsp; (opens in a new tab)" href="http://www.vishalchovatiya.com/7-advanced-cpp-concepts-idiom-examples-you-should-know/#Virtual-Constructor" target="_blank"><span style="color:#001aa3" class="color">virtual&nbsp;copy constructor</span></a>(i.e.&nbsp;<code>clone()</code>). </li><li>Make sure while using Abstract Factory you have ensured the <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/liskovs-substitution-principle-in-cpp-solid-as-a-rock/" target="_blank"><span style="color:#170cec" class="color">Liskov's Substitution Principle(LSP)</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Functional Approach to Factory Design Pattern using Modern C++</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>In our Abstract Factory example, we have followed the object-oriented approach but its equally possible nowadays to a more functional approach.</li><li>So, let's build a similar kind of Factory without relying on polymorphic functionality as it might not suit some time-constrained application like an <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Embedded_system" target="_blank"><span style="color:#0007a3" class="color">embedded system</span></a>. Because the <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/part-1-all-about-virtual-keyword-in-cpp-how-virtual-function-works-internally/" target="_blank"><span style="color:#072ad6" class="color">virtual table &amp; dynamic dispatch mechanism</span></a> may troll system during critical functionality.</li><li>This is pretty straight forward as it uses functional &amp; <a rel="noreferrer noopener" aria-label="lambda functions (opens in a new tab)" href="http://www.vishalchovatiya.com/learn-lambda-function-in-cpp-with-example/" target="_blank"><span style="color:#0002a3" class="color">lambda functions</span></a> as follows:</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"language":"cpp"} -->
```C++
struct Point { /* . . . */ };
struct Point2D : Point {/* . . . */};
struct Point3D : Point {/* . . . */};

class PointFunctionalFactory {
    map<PointType, function<unique_ptr<Point>() >>      m_factories;

public:
    PointFunctionalFactory() {
        m_factories[PointType::Point2D] = [] { return make_unique<Point2D>(); };
        m_factories[PointType::Point3D] = [] { return make_unique<Point3D>(); };
    }    
    unique_ptr<Point> create(PointType type) { return m_factories[type](); }  
};

int main() {
    PointFunctionalFactory pf;
    auto p2D = pf.create(PointType::Point2D);
    return EXIT_SUCCESS;
}
```
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>If you are thinking that we are over-engineering, then keep in mind that our object construction is simple here just to demonstrate the technique &amp; so does our lambda function. </li><li>When your object representation increases, it requires a lot of methods to call in order to instantiate object properly, in such case you just need to modify lambda expression of the factory or introduce <a href="http://www.vishalchovatiya.com/builder-design-pattern-in-modern-cpp/" target="_blank" rel="noreferrer noopener"><span style="color:#170cec" class="color">Builder Design Pattern</span></a>. </li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Benefits of Factory Design Pattern</h2>
<!-- /wp:heading -->

<!-- wp:list {"ordered":true} -->
<ol><li>Single point/class for different object creation. Thus easy to maintain &amp; understand software.</li><li>You can create the object without even knowing its type by using Abstract Factory.</li><li>It provides great modularity. Imagine programming a video game, where you would like to add new types of enemies in the future, each of which has different AI functions and can update differently. By using a factory method, the controller of the program can call to the factory to create the enemies, without any dependency or knowledge of the actual types of enemies. Now, future developers can create new enemies, with new AI controls and new drawing member functions, add it to the factory, and create a level which calls the factory, asking for the enemies by name. Combine this method with an XML description of levels, and developers could create new levels without having to recompile their program. All this, thanks to the separation of creation of objects from the usage of objects.</li><li>Allows you to change the design of your application more readily, this is known as loose coupling.</li></ol>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Summary by FAQs</h2>
<!-- /wp:heading -->

<!-- wp:yoast/faq-block {"questions":[{"id":"faq-question-1586176380514","question":["What is the correct way to implement the Factory Design Pattern in C++?"],"answer":["Abstract Factory \u0026 Functional Factory is always a good choice."],"jsonQuestion":"What is the correct way to implement the Factory Design Pattern in C++?","jsonAnswer":"Abstract Factory \u0026amp; Functional Factory is always a good choice."},{"id":"faq-question-1586176382912","question":["Factory vs Abstract Factor vs Functional Factory?"],"answer":["- Factory: Create an object with varied instantiation.",{"type":"br","props":{"children":[]}},"- Abstract Factor: Create an object without knowing its type \u0026 refer using base class pointer \u0026 reference. Access using polymorphic methods.",{"type":"br","props":{"children":[]}},"- Functional Factory: When object creation is more complex. Abstract Factory + ",{"type":"a","props":{"rel":"noreferrer noopener","href":"http://www.vishalchovatiya.com/builder-design-pattern-in-modern-cpp/","target":"_blank","children":[{"type":"span","props":{"style":"color:#9b51e0","class":"color","children":["Builder Design Pattern"]}}]}},". Although I have not included Builder in Functional Factory example."],"jsonQuestion":"Factory vs Abstract Factor vs Functional Factory?","jsonAnswer":"- Factory: Create an object with varied instantiation.\u003cbr/\u003e- Abstract Factor: Create an object without knowing its type \u0026amp; refer using base class pointer \u0026amp; reference. Access using polymorphic methods.\u003cbr/\u003e- Functional Factory: When object creation is more complex. Abstract Factory + \u003ca rel=\u0022noreferrer noopener\u0022 href=\u0022http://www.vishalchovatiya.com/builder-design-pattern-in-modern-cpp/\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#9b51e0\u0022 class=\u0022color\u0022\u003eBuilder Design Pattern\u003c/span\u003e\u003c/a\u003e. Although I have not included Builder in Functional Factory example."},{"id":"faq-question-1586176383617","question":["When to use the Factory Design Pattern?"],"answer":["Employ Factory Design Pattern to create an object of required functionality(s) but type of object will remain undecided or it will be decided ob dynamic parameters being passed."],"jsonQuestion":"When to use the Factory Design Pattern?","jsonAnswer":"Employ Factory Design Pattern to create an object of required functionality(s) but type of object will remain undecided or it will be decided ob dynamic parameters being passed."}]} -->
<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section" id="faq-question-1586176380514"><strong class="schema-faq-question">What is the correct way to implement the Factory Design Pattern in C++?</strong> <p class="schema-faq-answer">Abstract Factory &amp; Functional Factory is always a good choice.</p> </div> <div class="schema-faq-section" id="faq-question-1586176382912"><strong class="schema-faq-question">Factory vs Abstract Factor vs Functional Factory?</strong> <p class="schema-faq-answer">- Factory: Create an object with varied instantiation.<br/>- Abstract Factor: Create an object without knowing its type &amp; refer using base class pointer &amp; reference. Access using polymorphic methods.<br/>- Functional Factory: When object creation is more complex. Abstract Factory + <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/builder-design-pattern-in-modern-cpp/" target="_blank"><span style="color:#9b51e0" class="color">Builder Design Pattern</span></a>. Although I have not included Builder in Functional Factory example.</p> </div> <div class="schema-faq-section" id="faq-question-1586176383617"><strong class="schema-faq-question">When to use the Factory Design Pattern?</strong> <p class="schema-faq-answer">Employ Factory Design Pattern to create an object of required functionality(s) but type of object will remain undecided or it will be decided ob dynamic parameters being passed.</p> </div> </div>
<!-- /wp:yoast/faq-block -->


[Have Any Suggestions, Query or Wants to Say `Hi`? Take the Pressure Off, You Are Just a Click Away.](http://www.vishalchovatiya.com/contact-2/)🖱️