Click here to Skip to main content
15,894,740 members

Response to: Constructors : What does this statement mean?

Revision 1
Most often it doesn't matter whether you use member initializer lists or assignments inside the body of your constructor. For example in your case you can perform the initialization of your int members from both the initializer list and the body of your constructor. However sometimes you can intialize a member only from the initializer list, and sometimes you HAVE TO initialize some members if you don't want to get a compile error!
C++
class class_with_default_ctor
{
public:
    // this can act as a default ctor
    class_with_default_ctor(int _i=0)
        : i(_i)
    {}

    int i;
};

class class_without_default_ctor
{
public:
    class_without_default_ctor(int _i)
        : i(_i)
    {}

    int i;
};

class something
{
};

class test
{
public:
    test(something& sg)
        // You don't have to initialize m_class_with_default here but
        // you can do that if the default constructor doesn't do what
        // you want and other constructors are available. If you
        // don't call a default constructor here explicitly then
        // the compiler automatically calls the default constructor
        // of the class before the body of your ctor is executed so
        // later modifying the value of m_class_with_default in the
        // body of your constructor means that you initialize twice:
        // once by calling its default constructor and then when you
        // change it. You can avoid this double initialization by
        // explicitly calling a different constructor from the
        // initializer list, you can't do this from the ctor body.
        : m_class_with_default(5)
        // The following initializations are all MANDATORY and they
        // can be performed only from the initializer list! Not
        // initializing any of these from the initializer list leads
        // to a compile error!
        , m_class_without_default(6)
        , m_const_int(7)
        , m_const_something_ref(sg)
        , m_something_ref(sg)
    {
    }

private:
    class_with_default_ctor m_class_with_default;
    class_without_default_ctor m_class_without_default;
    const int m_const_int;
    const something& m_const_something_ref;
    something& m_something_ref;
};
Posted 4-Oct-12 13:27pm by pasztorpisti.
Tags: