Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I want to determine when to do non-trivial initialization of a class. I see two

ID: 653176 • Letter: I

Question

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]

Explanation / Answer

Always use the constructor unless there is a good reason not to. It's "The C++ Way" (tm).

Regarding your points to consider:

Constructors are always more or equally efficient as having code outside in separate init() functions.

Constructors tend to be easier to use for other developers. Without looking at your source or docs, I would expect new YourClass(stuff) to work. Having to call a yourClass->init(stuff) afterwards is not enforced by the compiler and it's an easy slip up to make.

As per number 2 - a lot of caveats about constructors are fleshed out by compilers for you, in terms of order of initialization etc. When you move things out of constructors you face the danger of reinventing the wheel, sometimes as a square.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote