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: 493
        
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]
 
© Programmers or respective owner