My $0.02:
Of course, as kbw pointed out... is depends on what you're doing. Though I tend to prefer "constructor does all the necessary prep work" because, after all, that's kind of what the constructor is for.
What's the point in having an uninitialized object? How is it beneficial?
IMO it makes code more complicated. IE, if the object is uninitialized, all of its members are going to have to fail somehow. To fail safely, each member is going to have to check to make sure the object is initialized before doing its actual work.
Whereas if the constructor does the initialization, and there is no "bad state"... then each member can safely assume the state of the object.
It also creates more error prone code. What if I create an object and forget to initialize it? That kind of defeats half the point of RAII.
It also makes less intuitive code. If I have a 'Window' object, I expect it to represent a window. Yet if I have to initialize it separately, it does not represent a window until I actually initialize it.
Conversely, take a look at std::thread. A thread object
is a thread. When you create the object, you create the thread. When the object is destroyed, so is the thread. The two are one and the same. Conceptually it just makes so much more sense.
The constructor route leaves very little customization left to the user in my opinion. |
How so? What can the user do with a separate 'Create' function that they can't just do with the constructor?
However with the function route, the class can be constructed and then it is up to the user to decide when get window is actually created. |
Well... constructing the class
is creating the window. If you don't want the window to be created, then don't construct the class. Why would you ever want to do one and not the other?