Question

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:

  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]

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top