1

This question is for C++11.

In the following struct A, will x always be 42, when the default constructor is used?

struct A{
  A() = default;
private:
  int x = 42;
}

In short, I'm wondering if the default constructor guarantees that default member values will be set.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Tyson Hilmer
  • 741
  • 7
  • 25

1 Answers1

1

Yes.

Unfortunately the wording below is from the standard draft as of today, but the principle is the same in C++11.

[class.default.ctor]/4 A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used ([basic.def.odr]) to create an object of its class type ([intro.object]), when it is needed for constant evaluation ([expr.const]), or when it is explicitly defaulted after its first declaration. The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-initializer ([class.base.init]) and an empty compound-statement.

[class.base.init]/9 In a non-delegating constructor, if a given potentially constructed subobject is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then:

  1. if the entity is a non-static data member that has a default member initializer ([class.mem]) and either
    1. the constructor's class is a union ([class.union]), and no other variant member of that union is designated by a mem-initializer-id or
    2. the constructor's class is not a union, and, if the entity is a member of an anonymous union, no other member of that union is designated by a mem-initializer-id, the entity is initialized from its default member initializer as specified in [dcl.init];

[..]


In short, I'm wondering if the default constructor guarantees that default member values will be set.

An example of exactly this follows the passage latterly quoted above.


However, if you were to define A::A() and provide an initialiser for x, it would take precedence over the inline initialiser.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    This answer is correct but much of the text you have quoted is not in the C++11 standard unfortunately (n3337). – P.W Apr 16 '19 at 12:16
  • @P.W Ah, shame. Might revisit it with C++11 wording if I can be bothered to dig it up but for now my time allotted to this question has expired! – Lightness Races in Orbit Apr 16 '19 at 12:18