Possible Duplicate:
Avoid having an initialization method

I want to determine when to do non-trivial initialization of a class. I see two times to do initialization: constructor and other method. I want to figure out when to use each.

Choice 1:

Constructor does initialization

MyClass::MyClass(Data const& data) : m_data()
    // does non-trivial initialization here

   // cleans up here

Choice 2:

Defer initialization to an initialize method

MyClass::MyClass() : m_data()

MyClass::Initialize(Data const& data)
    // does non-trivial initialization here

    // cleans up here

So to try and remove any subjectivity I want to figure out which is better in a couple of situations:

  1. Class that encapsulates a resource (window/font/some sort of handle)
  2. Class that composites resources to do something (a control/domain object)
  3. Data structure classes (tree/list/etc.)
  4. [Anything else you can think of]

Things to analyze:

  1. Performance
  2. Ease of use by other developers
  3. How error-prone/opportunities for bugs
  4. [Anything else you can think of]
  • 3
    I think the accepted is that apart from very rare situations that two phase initialization (call to Initialize()) is a bad idea as it potentially leaves the object in an invalid state. Constructor should fully initialize the object. – Martin York Nov 12 '12 at 17:52
  • 1
    I often find that in situations where RAII doesn't seem to fit, the name "Initialize" itself is actually a misnomer. Often, one isn't initializing the object per se, but just setting a context. – Kevin Hsu Nov 12 '12 at 18:15
  • @Loki Astari: Do you have a link to support this? Also, my understanding of 2-phase initialisation is that you have a class Factory function that creates the object and then calls an Init() before returning the pointer, which is different from a plain constructor calling Init(). – James Nov 12 '12 at 18:19
  • @James in what situations is that better, and how, than setting a context in the constructor by the said factory method? (I am not looking to argue, I am curious.) – MrFox Nov 12 '12 at 18:28

Always use the constructor unless there is a good reason not to. It's "The C++ Way" (tm).

Regarding your points to consider:

  1. Constructors are always more or equally efficient as having code outside in separate init() functions.

  2. Constructors tend to be easier to use for other developers. Without looking at your source or docs, I would expect new YourClass(stuff) to work. Having to call a yourClass->init(stuff) afterwards is not enforced by the compiler and it's an easy slip up to make.

  3. As per number 2 - a lot of caveats about constructors are fleshed out by compilers for you, in terms of order of initialization etc. When you move things out of constructors you face the danger of reinventing the wheel, sometimes as a square.

  • Also how does errors during initialization factor in? Constructors require exceptions to be thrown, which most people don't know when/how to catch if they want to handle errors. An Initialize method could be a bool and therefore be more straight forward that errors should be handling (but then we get into the whole error codes suck and exceptions rule thing...) – Bob Fincheimer Nov 12 '12 at 18:28
  • @BobFincheimer that is a good point. If you work for Google, you compile without exceptions and you use their style guide. IMHO that falls into the "good reason not to use constructors" category. The problem with init() error codes is that the constructor can still fail (though less likely), so now you have two potential points of failure and you are effectively ignoring one of them. – MrFox Nov 12 '12 at 18:33
  • 1
    I was playing devil's advocate... Constructors w/ exceptions is the best way to go, error codes are bad and very evil (checking for error codes cost time, try/catch is at most the same amount of cost, if not less) – Bob Fincheimer Nov 12 '12 at 18:58
  • "If you work for Google, you compile without exceptions" - really? That's non-standard C++, then. I'm not sure whether or not I find it surprising if Google are enforcing that. – underscore_d Jan 2 '16 at 11:49

Ideally, just use a constructor. It is usually a bad thing when a constructor returns a not-quite-usable object.

However, as people have pointed out, you often have situations where the data needed to fully initialize an object is not available at construction time. You can deal with a situation like that by using the Builder Pattern.

Let's say you have a class Foo, which requires some non-trivial initialization. You create a class FooBuilder, which simply stores all the data needed to initialize an object of Foo. FooBuilder would have a member function (aka method) Foo *build() or maybe Foo build(), which you would call when all the data is collected. It might also have setters for various items that need to be passed to Foo's constructor, and it might supply defaults for some of those.

This solves the problem of "late initialization" without requiring an initialize() member function. For example, if you need to create an array of Foo objects before you have all the stuff to initialize them, you would instead create an array of FooBuilders. Then you would call the appropriate setters on the builders as data becomes available. Finally, when all the data are safely stored in the builders, you create an array of Foo's, by calling build() on each builder.


One option that no one seemed to touch on is instead of constructing then Init, using a private constructor and a static Initialize function. Indeed this is a powerful technique because in theory the static initialize function might construct different subclasses based on context.

I would choose one or the other. As others have mentioned, having a constructor followed by an Initialize call is error prone.

  • so you are in the Constructor for initialization, and to also use the Factory pattern for anything that a constructor shouldn't do... – Bob Fincheimer Nov 12 '12 at 18:59
  • That's a good rule of thumb. – Michael Brown Nov 12 '12 at 19:01
  • 1
    But what is difference between static initialize method that returns constructed object, and constructor that takes the same arguments? – kolen Mar 6 '14 at 14:07

Use an Init() when you have to supply parameters to your object that you don't/can't know when you create the object.

You could also use it if your class's functionality could take along time to construct, e.g. initialising the playback of a video file involves file parsing, video codec matching and loading, audio codec matching and loading, resource acquisition. In this case you might to break up the creation into asynchronous steps so your user's app remains responsive and also allows then to cancel the operation.

  • 2
    In this case, wouldn't the constructor initialize with the name of the file, then more real names would be used (not init) for the methods that process/load/show the video content? – Bob Fincheimer Nov 12 '12 at 18:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.