Manuel Manuel - 1 year ago 143
C++ Question

Initializer list vs. initialization method

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
. With the first solution, I would either have to add an
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).

Answer Source

When creating an array(using vector, or allocating dynamically using new) you will have to explicitly call init on 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download