3 ms·
One good alternative to ctor+init() is a static factory method with a private ctor. It's just as simple as in C.
by pradn 7y ago
One good alternative to ctor+init() is a static factory method with a private ctor. It's just as simple as in C.
- fluffything 7y agoNot sure what a "factory method" is, but struct Foo { private: int a = 0, b = 0; Foo() = default; Foo(int a, int b): a(a), b(b) {} public: static Foo init_zeroed() { return Foo{}; } static Foo init_ones() { return Foo{1, 1}; } }; will do. You can add as many static methods acting as "named constructors" as you want.
- stickfigure 7y ago...and now you know what a "factory method" is.
- Koshkin 7y agoAlmost. One of the biggest advantages of a class factory is that it can return a pointer to an interface rather than a concrete class.
- inetknght 7y agoYes but that doesn't meaningfully change what a "factory" is: a factory returns an already-constructed object or smart-pointer-to-that-object you can work with. Whether or not that object is concrete or an interface to a hidden implementation is less important IMO.