Constructor Initialization Lists

Introduction

Assigning const or reference member variables values in the body of the constructor is not sufficient.
Const and reference variables must be initialized on the line they are declared.

When to use an Initialization List

  • No Default Constructor: If you have a field that has no default constructor (or a parent class with no default constructor), you must specify which constructor you wish to use.
  • References: If you have a field that is a reference, you also must initialize it in the initialization list; since references are immutable they can be initialized only once.

Initialization lists

Example 1: Explicit assignments in the constructor body

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

Example 2: The above code using an initializer list.

class Something
{
private:
    int m_nValue;
    double m_dValue;
    int *m_pnValue;
    const int m_Value;
public:
    Something() : m_nValue(0), m_dValue(0.0), m_pnValue(0),
m_Value(5)
    {
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.