Suppose you write an export feature. The procedure is the same for CSV and JSON: write the header, write each row, then finish. Only the writer object is different. If the base class that owns this procedure calls new CsvWriter directly, you must change the base class each time you add a format. The Factory Method pattern moves object creation into a virtual function, so subclasses decide which class to instantiate. This post covers the basic form, default implementations, and the parameterized factory method. It also covers the constructor trap, a CRTP variant, static factory functions, and a C implementation.
Structure
| Participant | Role | Example |
|---|---|---|
| Product | Interface of the objects that the factory method creates | Writer |
| ConcreteProduct | The actual product | CsvWriter, JsonWriter |
| Creator | Declares the factory method and owns the procedure that calls it | Exporter (run(), createWriter()) |
| ConcreteCreator | Overrides the factory method to return a ConcreteProduct | CsvExporter, JsonExporter |
Basic form
// exporter.cpp — the framework (run) is fixed; subclasses decide what to create
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Row { std::string name; int score; };
struct Writer {
virtual ~Writer() = default;
virtual void begin() {}
virtual void write(const Row &r) = 0;
virtual void end() {}
};
class Exporter {
public:
virtual ~Exporter() = default;
void run(const std::vector<Row> &rows) // fixed procedure
{
auto w = createWriter(); // call the factory method
w->begin();
for (const auto &r : rows)
w->write(r);
w->end();
}
protected:
virtual std::unique_ptr<Writer> createWriter() = 0; // factory method
};
struct CsvWriter : Writer {
void begin() override { std::cout << "name,score\n"; }
void write(const Row &r) override { std::cout << r.name << ',' << r.score << '\n'; }
};
struct JsonWriter : Writer {
bool first = true;
void begin() override { std::cout << '['; }
void write(const Row &r) override
{
std::cout << (first ? "" : ",") << "{\"name\":\"" << r.name << "\",\"score\":" << r.score << '}';
first = false;
}
void end() override { std::cout << "]\n"; }
};
struct CsvExporter : Exporter {
std::unique_ptr<Writer> createWriter() override { return std::make_unique<CsvWriter>(); }
};
struct JsonExporter : Exporter {
std::unique_ptr<Writer> createWriter() override { return std::make_unique<JsonWriter>(); }
};
int main()
{
std::vector<Row> rows = {{"kim", 90}, {"lee", 85}};
CsvExporter{}.run(rows);
JsonExporter{}.run(rows);
}$ g++ -std=c++20 -Wall -Wextra -O2 -o exporter exporter.cpp && ./exporter
name,score
kim,90
lee,85
[{"name":"kim","score":90},{"name":"lee","score":85}]
run() does not know which writer it gets. To add a format, you add one ConcreteCreator and one ConcreteProduct.
Factory method with a default implementation
The factory method does not have to be pure virtual. The base class creates a reasonable default product, and only the subclasses that need a different product override it.
// default_fm.cpp — factory method with a default; only some subclasses override it
#include <iostream>
#include <memory>
#include <string>
struct Connection {
virtual ~Connection() = default;
virtual std::string describe() const { return "TCP connection"; }
};
struct TlsConnection : Connection {
std::string describe() const override { return "TLS connection"; }
};
class Client {
public:
virtual ~Client() = default;
void request(const std::string &path)
{
auto c = makeConnection();
std::cout << "GET " << path << " over " << c->describe() << '\n';
}
protected:
virtual std::unique_ptr<Connection> makeConnection()
{ return std::make_unique<Connection>(); } // default
};
struct SecureClient : Client {
protected:
std::unique_ptr<Connection> makeConnection() override
{ return std::make_unique<TlsConnection>(); }
};
int main()
{
Client{}.request("/health");
SecureClient{}.request("/login");
}$ g++ -std=c++20 -Wall -Wextra -O2 -o default_fm default_fm.cpp && ./default_fm
GET /health over TCP connection
GET /login over TLS connection
Parameterized factory method
This form takes an identifier and creates one of several kinds of product. A subclass handles only the new identifiers and delegates the rest to the base class.
// param_fm.cpp — parameterized factory method: select the product by identifier
#include <iostream>
#include <memory>
#include <string_view>
struct Codec {
virtual ~Codec() = default;
virtual std::string_view name() const = 0;
};
struct Gzip : Codec { std::string_view name() const override { return "gzip"; } };
struct Zstd : Codec { std::string_view name() const override { return "zstd"; } };
struct Identity : Codec { std::string_view name() const override { return "identity"; } };
class Decoder {
public:
virtual ~Decoder() = default;
virtual std::unique_ptr<Codec> createCodec(std::string_view encoding) const
{
if (encoding == "gzip") return std::make_unique<Gzip>();
if (encoding == "" || encoding == "identity") return std::make_unique<Identity>();
return nullptr; // unknown encoding
}
};
// the subclass adds one identifier and delegates the rest to the base
class ModernDecoder : public Decoder {
public:
std::unique_ptr<Codec> createCodec(std::string_view encoding) const override
{
if (encoding == "zstd") return std::make_unique<Zstd>();
return Decoder::createCodec(encoding);
}
};
int main()
{
ModernDecoder d;
for (std::string_view e : {"gzip", "zstd", "", "br"}) {
auto c = d.createCodec(e);
std::cout << '"' << e << "\" -> " << (c ? c->name() : "unsupported") << '\n';
}
std::cout << "base zstd -> " << (Decoder{}.createCodec("zstd") ? "ok" : "unsupported") << '\n';
}$ g++ -std=c++20 -Wall -Wextra -O2 -o param_fm param_fm.cpp && ./param_fm
"gzip" -> gzip
"zstd" -> zstd
"" -> identity
"br" -> unsupported
base zstd -> unsupported
The base Decoder does not support "zstd", but ModernDecoder does. The subclass extends the supported set.
Why you must not call it from a constructor
In C++, while the base class constructor runs, the dynamic type of the object is still the base class. A virtual call in the constructor dispatches to the base version, not to the override.
// ctor_trap.cpp — a factory method called in the constructor is not the derived version
#include <iostream>
#include <memory>
#include <string>
struct Logger {
virtual ~Logger() = default;
virtual std::string name() const { return "ConsoleLogger"; }
};
struct FileLogger : Logger {
std::string name() const override { return "FileLogger"; }
};
class Service {
public:
Service() : log_(createLogger()) {} // trap
virtual ~Service() = default;
std::string loggerName() const { return log_->name(); }
protected:
virtual std::unique_ptr<Logger> createLogger() { return std::make_unique<Logger>(); }
private:
std::unique_ptr<Logger> log_;
};
struct FileService : Service {
protected:
std::unique_ptr<Logger> createLogger() override { return std::make_unique<FileLogger>(); }
};
// fix: two-phase initialization calls the factory method after construction
template <class T>
std::unique_ptr<T> make_initialized()
{
auto p = std::make_unique<T>();
p->init();
return p;
}
class Service2 {
public:
virtual ~Service2() = default;
void init() { log_ = createLogger(); }
std::string loggerName() const { return log_->name(); }
protected:
virtual std::unique_ptr<Logger> createLogger() { return std::make_unique<Logger>(); }
private:
std::unique_ptr<Logger> log_;
};
struct FileService2 : Service2 {
protected:
std::unique_ptr<Logger> createLogger() override { return std::make_unique<FileLogger>(); }
};
int main()
{
FileService s;
std::cout << "ctor call : " << s.loggerName() << '\n';
std::cout << "two-phase : " << make_initialized<FileService2>()->loggerName() << '\n';
}$ g++ -std=c++20 -Wall -Wextra -O2 -o ctor_trap ctor_trap.cpp && ./ctor_trap
ctor call : ConsoleLogger
two-phase : FileLogger
The object is a FileService, but it gets a ConsoleLogger. Use two-phase initialization (call the factory method from init() after construction) or lazy initialization instead.
A pure virtual factory method is worse. A direct call from the constructor fails at link time, and an indirect call through another member function aborts at run time.
// pure_direct.cpp — direct call from the constructor
#include <memory>
struct P { virtual ~P() = default; };
struct Base {
Base() { p = create(); }
virtual ~Base() = default;
virtual std::unique_ptr<P> create() = 0;
std::unique_ptr<P> p;
};
struct Derived : Base {
std::unique_ptr<P> create() override { return std::make_unique<P>(); }
};
int main() { Derived d; }$ g++ -std=c++20 -Wall -Wextra -O0 -o pure_direct pure_direct.cpp 2>&1 | grep -E 'warning|undefined|error'
pure_direct.cpp:5:28: warning: pure virtual ‘virtual std::unique_ptr<P> Base::create()’ called from constructor
pure_direct.cpp:(.text._ZN4BaseC2Ev[_ZN4BaseC5Ev]+0x4d): undefined reference to `Base::create()'
collect2: error: ld returned 1 exit status
// pure_trap.cpp — calling a pure virtual factory method from the constructor
#include <memory>
struct P { virtual ~P() = default; };
struct Base {
Base() { init(); } // indirect call
void init() { p = create(); }
virtual ~Base() = default;
virtual std::unique_ptr<P> create() = 0;
std::unique_ptr<P> p;
};
struct Derived : Base {
std::unique_ptr<P> create() override { return std::make_unique<P>(); }
};
int main() { Derived d; }$ g++ -std=c++20 -Wall -Wextra -O0 -o pure_trap pure_trap.cpp && ./pure_trap; echo "exit=$?"
pure virtual method called
terminate called without an active exception
bash: line 1: 33232 Aborted (core dumped) ./pure_trap
exit=134
CRTP: a factory method without virtual functions
If the Creator type is known at compile time, you can use the Curiously Recurring Template Pattern (CRTP) for static dispatch.
// crtp_fm.cpp — select the factory method at compile time without virtual functions (CRTP)
#include <iostream>
#include <memory>
#include <string>
struct Parser { virtual ~Parser() = default; virtual std::string kind() const = 0; };
struct IniParser : Parser { std::string kind() const override { return "ini"; } };
struct TomlParser : Parser { std::string kind() const override { return "toml"; } };
template <class Derived>
class ConfigLoader {
public:
void load(const std::string &path)
{
auto p = static_cast<Derived *>(this)->createParser(); // static dispatch
std::cout << path << " parsed with " << p->kind() << '\n';
}
};
struct IniLoader : ConfigLoader<IniLoader> {
std::unique_ptr<Parser> createParser() { return std::make_unique<IniParser>(); }
};
struct TomlLoader : ConfigLoader<TomlLoader> {
std::unique_ptr<Parser> createParser() { return std::make_unique<TomlParser>(); }
};
int main()
{
IniLoader{}.load("app.ini");
TomlLoader{}.load("Cargo.toml");
}$ g++ -std=c++20 -Wall -Wextra -O2 -o crtp_fm crtp_fm.cpp && ./crtp_fm
app.ini parsed with ini
Cargo.toml parsed with toml
The tradeoff: IniLoader and TomlLoader have no common base class, so you cannot store them in one container.
Static factory functions are a different idiom
Much of what developers call a “factory method” is not the GoF pattern. It is the named constructor idiom: a static function that creates the object in place of a constructor. It needs no inheritance, and it can report failure with std::optional or a similar type.
// named_ctor.cpp — static factory function (named constructor): a different idiom from the GoF factory method
#include <charconv>
#include <cstdint>
#include <iostream>
#include <optional>
#include <string_view>
class Color {
public:
static Color fromRgb(std::uint8_t r, std::uint8_t g, std::uint8_t b) { return {r, g, b}; }
static std::optional<Color> fromHex(std::string_view s)
{
if (s.size() != 7 || s[0] != '#')
return std::nullopt;
unsigned v = 0;
auto [p, ec] = std::from_chars(s.data() + 1, s.data() + 7, v, 16);
if (ec != std::errc{} || p != s.data() + 7)
return std::nullopt;
return Color(v >> 16, (v >> 8) & 0xff, v & 0xff);
}
void print() const { std::cout << "rgb(" << +r_ << ',' << +g_ << ',' << +b_ << ")\n"; }
private:
Color(std::uint8_t r, std::uint8_t g, std::uint8_t b) : r_(r), g_(g), b_(b) {}
std::uint8_t r_, g_, b_;
};
int main()
{
Color::fromRgb(255, 128, 0).print();
for (auto s : {"#1e90ff", "#zzzzzz", "1e90ff"}) {
auto c = Color::fromHex(s);
std::cout << s << " -> ";
c ? c->print() : void(std::cout << "invalid\n");
}
}$ g++ -std=c++20 -Wall -Wextra -O2 -o named_ctor named_ctor.cpp && ./named_ctor
rgb(255,128,0)
#1e90ff -> rgb(30,144,255)
#zzzzzz -> invalid
1e90ff -> invalid
| GoF factory method | Static factory function | |
|---|---|---|
| Form | Virtual member function | static member function |
| What varies | The type that the subclass creates | The way of construction (input format, validation) |
| Inheritance | Required | Not required |
| Example | Exporter::createWriter() | Color::fromHex(), std::make_unique |
C implementation
In C, a struct that holds a creation callback is the Creator. The procedure function does not know what the callback creates.
/* exporter.c — in C, a struct with a "create callback" acts as the factory method */
#include <stdio.h>
#include <stdlib.h>
struct writer {
void (*write)(struct writer *w, const char *name, int score);
void (*finish)(struct writer *w);
int count;
};
struct exporter {
const char *label;
struct writer *(*create_writer)(void); /* factory method */
};
static void csv_write(struct writer *w, const char *n, int s) { printf("%s,%d\n", n, s); w->count++; }
static void csv_finish(struct writer *w) { printf("# %d rows\n", w->count); free(w); }
static void tsv_write(struct writer *w, const char *n, int s) { printf("%s\t%d\n", n, s); w->count++; }
static void tsv_finish(struct writer *w) { free(w); }
static struct writer *new_writer(void (*wr)(struct writer *, const char *, int),
void (*fin)(struct writer *))
{
struct writer *w = calloc(1, sizeof(*w));
if (!w)
abort();
w->write = wr;
w->finish = fin;
return w;
}
static struct writer *csv_create(void) { return new_writer(csv_write, csv_finish); }
static struct writer *tsv_create(void) { return new_writer(tsv_write, tsv_finish); }
/* fixed procedure: it does not know which writer it gets */
static void exporter_run(const struct exporter *e)
{
struct writer *w = e->create_writer();
printf("[%s]\n", e->label);
w->write(w, "kim", 90);
w->write(w, "lee", 85);
w->finish(w);
}
int main(void)
{
const struct exporter csv = { "csv", csv_create };
const struct exporter tsv = { "tsv", tsv_create };
exporter_run(&csv);
exporter_run(&tsv);
return 0;
}$ gcc -std=c11 -Wall -Wextra -O2 -fsanitize=address -o exporter_c exporter.c && ./exporter_c
[csv]
kim,90
lee,85
# 2 rows
[tsv]
kim 90
lee 85
The Linux kernel’s struct file_system_type has a similar shape. The VFS owns the mount procedure, and each file system fills in its private data and operations in the int (*init_fs_context)(struct fs_context *) callback.
Comparison with Abstract Factory
| Factory Method | Abstract Factory | |
|---|---|---|
| Creates | One product | A family of related products |
| Extension mechanism | Inheritance (Creator subclass) | Composition (inject a factory object) |
| Caller | The Creator’s own procedure (run()) | An external client that receives the factory |
Cautions
- Do not call it from a constructor or destructor. In the destructor, the derived part is already destroyed, so the base version runs.
- Each product needs a Creator subclass. The number of classes grows with the number of products. If you only need to change creation, inject a factory function as
std::functioninstead. - Handle
nullptrin the parameterized form. If you do not define the result for an unknown identifier, the caller dereferences null. You can also throw an exception or return a default product. - Return
std::unique_ptr. The caller can convert it tostd::shared_ptrwhen it needs shared ownership. The reverse conversion is not possible. - Covariant return types work only with raw pointers. You can narrow the return type, as in
Derived* create() override, only for raw pointers and references, not forunique_ptr.
Conclusion
Factory Method applies the split “the base class owns the procedure, the subclass supplies the parts” to object creation. It often appears together with the Template Method pattern, and each creation operation of an Abstract Factory is usually a factory method.
This is a referral link. I may receive credit if you sign up, at no extra cost to you.
Try it on a cloud server — Deploy Ubuntu on VultrReferences
- Erich Gamma et al., Design Patterns: Elements of Reusable Object-Oriented Software (GoF), Factory Method
- isocpp FAQ — Calling virtual functions from constructors
- Refactoring.Guru — Factory Method