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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With