C++ - Constructor or Initialize Method to Startup [duplicate]
https://softwareengineering.stackexchange.com/questions/175594
-
05-11-2019 - |
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:
- 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]
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with softwareengineering.stackexchange