which way for constructor is best?

c++, constructor

Solution

Performance:

The first one is the best because it initializes the objects in true sense unlike second method which assigns the already initialized objects.

Note that there is a little overhead when you use the second method:

As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.

Cost of Member Initialization = Object Construction 
Cost of Member Assignment = Object Construction + Assignment

In case of members which are in-built/POD data types there is no overhead but if the members are non POD types then the overhead is significant.

Necessity:

Note that You will be forced to use the member initializer list in certain scenarios:

- Your class has a reference member

- Your class has a non static const member

Such members cannot be assigned to but they must be initialized in member initializer list.

Given the above as a practice the first method is always preferrable.

Problem

There are two ways construct a class: ``` class Cell{ public: Cell(int cellID, int nx); ~Cell(); private: int cellID_; int nx; }; ``` The first way: ``` Cell::Cell(int cellID, int nx) : cellID_(cellID), nx_(nx){} ``` The second way : ``` Cell::Cell(int cellID, int nx){init(cellID, nx)} void Cell::init(int cellID, int nx){ cellID_ = cellID; nx_ = nx; } ```

Original source