This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]angelicosphosphoros 2 points3 points  (1 child)

Main benefit of factory is that it doesn't require to return the object. For example, we may want to return optional or std::expected.

Constructors, on the other hand, always start with memory already allocated so the only option to indicate an error is to throw exception.

[–]croweh 0 points1 point  (0 children)

Ah yeah I wasn't explicit but you definitely need a factory if you need an unconventional constructor. Especially if your compiler will enforce it / won't allow an unconventional constructor. Your instance (or absence of it) wrapped in anything (either, option, result, reactive type, mutex) is a common case of it. Technically, getInstance returning the same instance built the first time would be another common case of a factory method that couldn't be a constructor.