<<<Index>>>

Initializer list order

  • Initializer list order is restricted by the order of data member declarations in your class!

  • Because constructor call order is *very* important, modern compilers will generate errors when initializer list does not follow the order of class data members!

// point.h
class Graph { /*...*/ };
class Point {
private:
    Graph& m_g;
    int    m_x;
    int    m_y;
public:
    Point( Graph& g, int x, int y );
};
// point.cpp
Point::Point( Graph& g, int x, int y )
:
    m_x( x ),
    m_y( y ),
    m_g( g )  // out of order
{
}
// main.cpp
void main()
{
    Graph gr;
    Point pt( gr, 10, 20 );
}
  • When compiled with GNU GCC compiler version 3.4.5:

        main.cpp: In constructor 'Point::Point(Graph&, int, int)':
        main.cpp:9: warning: 'Point::m_g' will be initialized after
        main.cpp:7: warning:   'int Point::m_x'
        main.cpp:20: warning:   when initialized here
<<<Index>>>