Tuesday, 10 June 2014

Initialization List

            C++ provides another way of initializing member variables that allows us to initialize member variables when they are created rather than afterwards. This is done through use of an initialization list.

Using an initialization list is very similar to doing implicit assignments.


Example without initialization list.
class Something
{
private:
    int m_nValue;
    double m_dValue;
    int *m_pnValue;
public:
    Something()
    {
        m_nValue = 0;
        m_dValue = 0.0;
        m_pnValue = 0;
    }
};


Now let’s write the same code using an initialization list:



class Something
{
private:
    int m_nValue;
    double m_dValue;
    int *m_pnValue;
public:
    Something() : m_nValue(0), m_dValue(0.0), m_pnValue(0)
    {
    }
};



The initialization list is inserted after the constructor parameters, begins with a colon (:), and then lists each variable to initialize along with the value for that variable separated by a comma. Note that we no longer need to do the explicit assignments in the constructor body, since the initialization list replaces that functionality. Also note that the initialization list does not end in a semicolon.




It is better to initialize all class variables in Initializer List instead of assigning values inside body. 

Basically without initializer list it takes one more operation to do the work, which is bad. So always use initialization list.

No comments:

Post a Comment