Search code examples
c++initializationdefault-constructor

Difference in Private Member Initializations in Constructor (C++)


I've been away from C++ for awhile and I am trying to determine the difference between these two default constructor initializations of a defined class's private member variables (if any). The class definition is in a header file while the implementation is in a separate file. All private member variables need to be initialized to "0" or a non-meaningful value.

NOTE:

int data[MAX_SIZE] is a fixed size compile time array. int used: is an index tracker for the array.

Generally speaking, I'm accustomed to initializing members in the following way:

 // Default Constructor
 IntSet::IntSet()
 {
    data[MAX_SIZE-1] = {0}
    used = 0;
 }

I'm combing through some legacy code and finding a completely different syntax:

 // Default Constructor
 IntSet::IntSet() : used(0)
 {
    data[MAX_SIZE-1] = {0};
 }

Is there a difference in the end result?


Solution

  • Members are initialized when they are constructed, before the body of the constructor is reached. There are cases where they differ. For example:

    • if a member is const or a reference, it must be initialized in the initializer list, and cannot be initialized in the constructor body

    • if the member has no default constructor (or you don't have access to it), then you must provide the constructor it should use some arguments, and that can only be done in the initializer list.

    • if the object is "big and expensive" to create and also to assign to, then you could be doing something inefficiently by default constructing the object and then using the assignment operator on it. (Rather than constructing it with its initial value at the same time.)

    For integers and primitive, POD types like you described default construction is trivial and so either way is equivalent, given the above restrictions on reference, const, etc.