Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ default member initialization and constructors

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

class Foo {
public:
  Foo(int argX) : Foo(argX, defaultYValue) {}
  Foo(int argX, int argY) : x(argX), y(argY) {};
private:
  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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading