Constructor vs. Object.Create()

Which method of creating an object would the best? I've seen people who create objects using the constructor alone and I've seen people who use a Create() method to initialize the object.

// Constructor initialization
Foo bar(args);

// Create() method
Foo bar;

What is the difference between the two methods? Why one over the other?
The first is called RAII. When you can use it you should. But there are several instances where you won't, but use some kind of factory instead. Nevertheless, RAII is the important concept here.

The second form is called two stage construction. It's a common pattern in MFC for example. You'd only resort to this if you can't do RAII.

RAII is important because it's an important tool in implementing exception guarantees.
Last edited on
Thank you for the reply. It has answered my question. :)
However, could you provide an example or two of a situation when RAII couldn't work? I can't think of any.

Also, if RAII is preferred why do people build entire libraries around two-stage construction?
However, could you provide an example or two of a situation when RAII couldn't work?

One example is when the initialisation of the object requires a call to a virtual method of that object . You can't make that method call in the constructor, because the vtable of an object isn't guaranteed to be fully created until after the construction of the object has been completed - i.e. after all the constructors have finished.

When that happens, you need a second stage, so that you can perform that initialisation after the object has been constructed.
closed account (S6k9GNh0)
kbw, the second method can also be a form of RAII, having more to do with how exceptions are handled. It's not always a smart idea to throw an exception in the constructor (rather, this is a caveat in the C++ FQA which is one of the few complaints that are valid). You can just hold a validation boolean, then check it during destruction. Not very pretty but yeah.

EDIT: For arguments sake though, it's not the worst evil to throw excceptions in the constructor. The conditions are slightly confusing:
Last edited on
It's not a valid complaint, it's the necessary and expected part of RAII
Last edited on
Topic archived. No new replies allowed.