The factory pattern

Let one function decide which class to build. Plus what AddressSanitizer and two warning flags find in the repository's version, and a fix.

What you'll learn
  • Separate creating an object from using it, through an abstract base class
  • Explain virtual dispatch through a base-class pointer
  • Fix the ownership problems of a factory that returns raw pointers

Code that uses an object should not have to know exactly which class it is. A factory takes that decision away from the caller: it receives a request — here an integer ID — and returns a pointer to the base class.

class Product {
public:
    virtual void print_product() = 0;     // abstract: no Product objects
};

class Product1 : public Product { /* prints "Hello from product 1." */ };
class Product2 : public Product { /* prints "Hello from product 2." */ };

Product *ProductFactory::createProduct(int ID) {
    if (ID == 0) return new Product1();
    else if (ID == 1) return new Product2();
    else return nullptr;
}
Class diagram of 02_factory.cpp. ProductFactory has a private static instance and private constructor, a static get_instance method and createProduct(int ID), and returns Product pointers. Product is abstract with a pure virtual print_product. Product1 and Product2 inherit from Product and implement print_product. ID 0 gives a new Product1, ID 1 a new Product2, any other ID nullptr. A note warns that Product has no virtual destructor, so deleting through a Product pointer would be undefined behaviour. Class diagram of 02_factory.cpp. ProductFactory has a private static instance and private constructor, a static get_instance method and createProduct(int ID), and returns Product pointers. Product is abstract with a pure virtual print_product. Product1 and Product2 inherit from Product and implement print_product. ID 0 gives a new Product1, ID 1 a new Product2, any other ID nullptr. A note warns that Product has no virtual destructor, so deleting through a Product pointer would be undefined behaviour.
main() only ever sees ProductFactory and Product*. Which concrete class it gets is decided in one place.

main() holds a Product *p and calls p->print_product(). Because the method is virtual, the call goes through the object’s vtable and runs the concrete class’s version, so the program prints Hello from product 1. and Hello from product 2.. Adding a Product3 means changing the factory and nothing else. The factory itself is a singleton (lesson 3), which the code notes is a common choice.

createProduct(0), (1) and (2), each followed by p->print_product(). The first two dispatch to the right class; ID 2 returns nullptr, and calling through it crashes, as the real program does.

What the tools find

The program runs correctly as written, but three problems surface as soon as it is used for anything more:

  1. Leaks. Neither product is ever deleted — p is simply overwritten. Built with -fsanitize=address, the run ends with 16 byte(s) leaked in 2 allocation(s): two 8-byte objects, each nothing but a vtable pointer.
  2. No virtual destructor. Deleting them would not be safe either. With -Wnon-virtual-dtor, GCC warns that Product has virtual functions and an accessible non-virtual destructor: delete p on a Product* that points at a Product1 is undefined behaviour.
  3. An unchecked nullptr. Any ID other than 0 or 1 returns nullptr, and main() calls through the result unconditionally. Changing the second request to createProduct(2) ends the program with a segmentation fault (exit status 139).

A safer factory

class Product {
public:
    virtual ~Product() = default;          // safe to delete through Product*
    virtual void print_product() = 0;
};

std::unique_ptr<Product> createProduct(int ID) {
    switch (ID) {
        case 0: return std::make_unique<Product1>();
        case 1: return std::make_unique<Product2>();
        default: return nullptr;
    }
}

for (int id : {0, 1, 2}) {
    auto p = createProduct(id);
    if (p) p->print_product();
    else std::cout << "no product with ID " << id << std::endl;
}                                          // each product is freed here

std::unique_ptr makes ownership explicit: the caller owns the product, and it is destroyed when p goes out of scope. The virtual destructor makes that destruction correct. Compiled with -Wall -Wextra -Wnon-virtual-dtor and run under AddressSanitizer and UndefinedBehaviorSanitizer, this version prints both greetings and no product with ID 2, with no warnings and no leaks. A free function also suffices here — the factory holds no state, so it does not need to be a singleton object at all.

Try it yourself. Replace the integer IDs with an enum class ProductType and let the compiler warn you (with -Wswitch) when a new enumerator is not handled. Then add a Product3 and count how many files change in the split factory/ version of the code.

View source on GitHub →