C++ default member initialization and constructors

I would like to know where I can find some documentation about the following behavior:

class Foo {
  Foo(int argX) : Foo(argX, defaultYValue) {}
  Foo(int argX, int argY) : x(argX), y(argY) {};
  const int x;
  const int y;
  const int defaultYValue = -1;

Might it be possible that y value is undefined ? Or is there some documentation in the standard that tells that it works (I did noticed that the default member initialization is discarded if it is otherwise overridden inside the constructor)

PS: this was discovered while forgetting the static for defaultYValue.

>Solution :

Yes, the code has undefined behavior. When using a delegating constructor it is the delegating constructor that will initialize the class members. When you pass defaultYValue to the delegating constructor, it has not yet be initialized so you are passing an uninitialized value to the delegate, and said delegate uses that value to set y.

This is called out by [class.base.init]/7

The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of [dcl.init] for direct-initialization.

Leave a Reply