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
}
MyClass::~MyClass()
{
// 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
}
MyClass::~MyClass()
{
// cleans up here
}
So to try and remove any subjectivity I want to figure out which is better in a couple of situations:
- Class that encapsulates a resource (window/font/some sort of handle)
- Class that composites resources to do something (a control/domain object)
- Data structure classes (tree/list/etc.)
- [Anything else you can think of]
Things to analyze:
- Performance
- Ease of use by other developers
- How error-prone/opportunities for bugs
- [Anything else you can think of]
-
3I 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.Loki Astari– Loki Astari2012年11月12日 17:52:22 +00:00Commented Nov 12, 2012 at 17:52
-
1I 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– Kevin Hsu2012年11月12日 18:15:17 +00:00Commented Nov 12, 2012 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– James2012年11月12日 18:19:31 +00:00Commented Nov 12, 2012 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– MrFox2012年11月12日 18:28:11 +00:00Commented Nov 12, 2012 at 18:28
4 Answers 4
Always use the constructor unless there is a good reason not to. It's "The C++ Way" (tm).
Regarding your points to consider:
Constructors are always more or equally efficient as having code outside in separate init() functions.
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 ayourClass->init(stuff)
afterwards is not enforced by the compiler and it's an easy slip up to make.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– Bob Fincheimer2012年11月12日 18:28:57 +00:00Commented Nov 12, 2012 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– MrFox2012年11月12日 18:33:30 +00:00Commented Nov 12, 2012 at 18:33
-
1I 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– Bob Fincheimer2012年11月12日 18:58:15 +00:00Commented Nov 12, 2012 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– underscore_d2016年01月02日 11:49:28 +00:00Commented Jan 2, 2016 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 FooBuilder
s. 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– Bob Fincheimer2012年11月12日 18:59:23 +00:00Commented Nov 12, 2012 at 18:59
-
That's a good rule of thumb.Michael Brown– Michael Brown2012年11月12日 19:01:45 +00:00Commented Nov 12, 2012 at 19:01
-
1But what is difference between static initialize method that returns constructed object, and constructor that takes the same arguments?kolen– kolen2014年03月06日 14:07:06 +00:00Commented Mar 6, 2014 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.
-
3In 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– Bob Fincheimer2012年11月12日 18:30:27 +00:00Commented Nov 12, 2012 at 18:30
Explore related questions
See similar questions with these tags.