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.
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:
- if the entity is a non-static data member that has a default member initializer (
[class.mem]
) and either
- 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- 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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments