C++ - Constructor or Initialize Method to Startup
- by Bob Fincheimer
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]