vigs1990
vigs1990

Reputation: 1699

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)

Upvotes: 4

Views: 151

Answers (3)

Luchian Grigore
Luchian Grigore

Reputation: 258648

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.

Upvotes: 6

Ivan Shcherbakov
Ivan Shcherbakov

Reputation: 2113

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

Upvotes: 3

jrok
jrok

Reputation: 55425

It's called initializer list and it initializes the fields with the values specified in the brackets. The following would achieve the same end effect:

Packet()
{
    bits_ = nullptr;  // or 0 or NULL pre-C++11
    datalen_ = 0;
    next_ = nullptr;
}

The difference is that in my example you're doing assignment, the fields would already be constructed by their default constructor.

For user-defined types with no default constructor, initializer list is the only way, since you need to provide some parameters to the constructor.

Upvotes: 2

Related Questions