class Alpha
{
private:
int data;
public:
Alpha() : data (0) // no argument constructor
{}
Alpha(int d) : data(0) // <- here assigning 0 to data before data will be assigned with d ??? // one argument constructor
{ data = d; }
I am working on example from book where they didn't initialize data it was my modification,
and I was wondering if that is sensible approach or would as you suggest be better to use this format
There's no benefit in assigning zero to the value and then immediately assigning another value. Just assign it to the value you want, in the initialisation list.
Your second constructor is doing double initialization (actually an initialization and an assignment). There is no point in doing so. kbw's example is preferred.
A further simplification would be:
1 2 3 4 5 6
class Alpha
{ int data;
public:
Alpha(int d = 0) : data (d) // defaults to 0 if no argument
{}
};
For variables of simple built-in types (that we call Plain Old Data Types of PODS), there isn't much difference as it's straightforward for the optimizer to remove d = 0.
However, if the member is another object, you can see that it gets initialized, then assigned. This can be expensive. So I would recommend that you initialize members in the initializer list where possible.
For example:
1 2 3 4 5 6
class A
{
std::string s;
public:
A(const std::string& str) { s = str; } // default string constructor then assignment is used
};