Constructors

Jun 5, 2017 at 11:03am
Hi there
I have question does this make sense?

thanks :)

1
2
3
4
5
6
7
8
9
10
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; }
Jun 5, 2017 at 11:14am
Yes, but in the second one, you could do:
1
2
Alpha(int d) : data (d)
{}
Jun 5, 2017 at 12:23pm
Hi KBW

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

1
2
Alpha (int d) : data(d)
{}
Jun 5, 2017 at 12:34pm
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.
Jun 5, 2017 at 12:41pm
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
    {}
};



Jun 5, 2017 at 12:43pm
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
};
Jun 5, 2017 at 12:52pm
thank you all :)

that is very informative! noted in my manual for future use.
Topic archived. No new replies allowed.