C++ - Constructor or Initialize Method to Startup

Posted by Bob Fincheimer on Programmers See other posts from Programmers or by Bob Fincheimer
Published on 2012-11-12T17:44:55Z Indexed on 2012/11/12 23:13 UTC
Read the original article Hit count: 388

Filed under:
|
|

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]

© Programmers or respective owner

Related posts about c++

Related posts about class-design