There are at least two ways to initialize a class in C++.
(1) Initializer List
struct C
{
int i;
C() : i(0) {}
};
(2) Initializer Method
struct D
{
int i;
C() { init(); }
void init() {
i = 0;
}
};
I need to re-init objects of my class from time to time. With the second solution, I can simply call obj.init(). With the first solution, I would either have to add an init() function which essentially duplicates the initializer list effect or use obj = C().
Is there a more-or-less consensus on what variant is better here? Is there a disadvantage to using an initializer method (except the possible loss of performance as mentioned in the C++ FAQ).
When creating an array (using vector, or allocating dynamically using
new) you will have to explicitly calliniton each of its members while using a constructor, it will automatically be called for all elements.I prefer placing basic initialization into the constructor and more complex logic into an init method. In my opinion a constructor should not perform any complex operations.