7

For example, is it safe to call Area() here:

Polygon::Polygon( Coord x0, Coord y0, Coord x1, Coord y1 )
    : m_BoundingBox( x0, y0, x1, y1 ), m_Area( m_BoundingBox.Area() )
{
}

That is, can one assume that members in the : , portion of a constructor are constructed and initialized in the order they are listed?

Michael
  • 5,775
  • 2
  • 34
  • 53

2 Answers2

13

It depends on the order of the members m_BoundingBox and m_Area in the class definition.

The standard states:

12.6.2/10 In a non-delegating constructor, initialization proceeds in the following order:

— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.

— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

So the members are not initialized in the order in which they appear in the mem-initializer, but on their odrer in the class definition.

Here you can see an online example of what happens if the elements are in the right or in the wrong order in the class.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • 1
    Modern compilers will warn if you put the initializers in a different order – M.M Aug 03 '15 at 23:19
  • 3
    and, to finish answering OP's question, it is safe to use previously-initialized members in later initializers – M.M Aug 03 '15 at 23:21
3

Nope, they are initialized in the order in which they are declared in the class block. The order in the initialization list has no effect (and that's why many compilers emit a warning when they do not match).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299