C++ static factory constructor

c++, constructor, factory

Solution

Your code currently contains a memory leak: any object created using `new`, must be cleaned up using `delete`. The `createWithID` method should preferably not use `new` at all and look something like this:

static Object createWithID(int id) 
{
    Object obj;
    obj.id = id;
    return obj; 
}

This appears to require an additional copy of the object, but in reality return value optimization will typically cause this copy to be optimized away.

Problem

I am in the process of making a simulation and it requires the creation of multiple, rather similar models. My idea is to have a class called Model and use static factory methods to construct a model. For example; Model::createTriangle or Model::createFromFile. I took this idea from previous java code and was looking for ways to implement this in C++. Here is what I came up with so far: ``` #include <iostream> class Object { int id; public: void print() { std::cout << id << std::endl; } static Object &createWithID(int id) { Object *obj = new Object(); obj->id = id; return *obj; } }; int main() { Object obj = Object::createWithID(3); obj.print(); return 0; } ``` Some questions about this: - Is this an accepted and clean way of making objects? - Does the returned reference always ensure correct removal of the object? - Is there any way to do this without pointers?

Original source

Related problems