Factory
A factory is a function (or type) that creates objects so callers do not write new or name a concrete class. In C++ it should return ownership: std::unique_ptr<Shape>, not a raw pointer.
Detailed Explanation
Circle c; needs a complete Circle at the call site. A scene loader that reads "circle" from a file cannot name every subclass in the loader if you want plugins. A factory maps a key to a constructor: unique_ptr<Shape> makeShape(string_view type). The loader depends on Shape and the factory, not on Circle.
Forms:
- Free function.
make_unique<Circle>(r)is already a factory. YourmakeShapeis a switch or a map of factories. - Static method.
Shape::fromJson(json)keeps construction next to the type. - Abstract factory. An interface
DeviceFactorywithcreateTexture(),createBuffer()implemented per backend (Vulkan, GL). Rarely needed until you have two families of products. - Registry. Types register a lambda into a
map<string, function<unique_ptr<Shape>()>>. Plugins push into the map at static init (watch the init-order fiasco; register frommainif you can).
Return type is the ownership decision. unique_ptr<Base> is the default. shared_ptr<Base> if the factory is not the unique owner. A raw Base* is a leak waiting for a missing delete. A value Shape slices.
Factories hide new and they hide which type. Do not add a factory in front of every constructor. User{"ada"} is clearer than UserFactory::create("ada") when there is one class and no polymorphism.
Argument forwarding: template<class T, class... A> unique_ptr<T> make(A&&... a) { return make_unique<T>(forward<A>(a)...); } is make_unique. Your factory adds the decision, not the forwarding.
Error policy: return nullptr or optional if the key is unknown; throw if a missing type is a broken config. Pick one and document it.
Code Examples
#include <memory>
#include <string_view>
struct Shape {
virtual ~Shape() = default;
virtual const char* name() const = 0;
};
struct Circle : Shape {
const char* name() const override { return "circle"; }
};
struct Square : Shape {
const char* name() const override { return "square"; }
};
std::unique_ptr<Shape> makeShape(std::string_view type) {
if (type == "circle") return std::make_unique<Circle>();
if (type == "square") return std::make_unique<Square>();
return nullptr;
}
int main() {
auto s = makeShape("circle");
return s && s->name()[0] == 'c' ? 0 : 1;
}Common Gotchas
Static registration of plugins
two translation units registering during static init can race or depend on order. Register from an explicit `init` if the set is not trivial.
A factory that always returns one type is a named constructor
fine for parsing; do not build a class hierarchy for it.
Slicing if you return `Shape` by value
the unique parts of `Circle` are gone.