Search code examples
c++constructorinitializationinitialization-list

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)


Solution

  • 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.