Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Constructor Understanding

Consider this constructor: Packet() : bits_(0), datalen_(0), next_(0) {}

Note that bits_, datalen_ and next_ are fields in the class Packet defined as follows:

u_char* bits_;
u_int datalen_;
Packet* next_;

What does this part of the constructor mean? bits_(0), datalen_(0), next_(0)

like image 701
vigs1990 Avatar asked Dec 21 '22 23:12

vigs1990


2 Answers

That's an initializer list, it sets the values to the ones specified.

Packet() : bits_(0), datalen_(0), next_(0)
{
    assert( bits_ == 0 );
    assert( datalen_ == 0);
    assert( next_ == 0);
}
//...
Packet()
{
    //bits_ , datalen_, next_ uninitialized here
}

Some members (const members or user-defined class members with no default constructors) can't be initialized outside the initializer list:

class A
{
    const int x;
    A() { x = 0; }  //illegal
};

class A
{
    const int x;
    A() : x(0) { }  //legal
};

It's also worth mentioning that double initialization won't occur using this technique:

class B
{
public:
   B() { cout << "default "; }
   B(int) { cout << "b"; }
};

class A
{
   B b;
   A() { b = B(1); }   // b is initialized twice - output "default b"
   A() : b(1) { }      // b initialized only once - output "b"
}; 

It's the preffered way of initializing members.

like image 188
Luchian Grigore Avatar answered Dec 23 '22 14:12

Luchian Grigore


This means that first bits_, then datalen_ and finally next_ will receive the value of 0. I.e. the following 2 code snippets are completely equivalent:

Packet()
     : bits_(0)
     , datalen_0)
     , next_(0)
{
}

and this:

Packet()
{
    bits_ = 0;
    datalen_ = 0;
    next_ = 0;
}

Beware, though. The initialization order is determined by member declaration order. I.e. the following code won't work as could have expected:

struct Packet
{
    int first;
    int second;

    Packet()
        : second(0)
        , first(second)
    {
    }
};

it will be equivalent to this:

struct Packet
{
    int first;
    int second;

    Packet()
    {
        first = second;
    second = 0;
    }
};

so second will receive a 0, but first won't

like image 31
Ivan Shcherbakov Avatar answered Dec 23 '22 13:12

Ivan Shcherbakov