It's not initialized twice; the default member initializer is just ignored. So for A a(555);
, a.k
is initialized as 555
.
If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.
From the standard, [class.base.init]/10:
If a given non-static data member has both a default member
initializer and a mem-initializer, the initialization specified by the
mem-initializer is performed, and the non-static data member's default
member initializer is ignored. [ Example: Given
struct A {
int i = /* some integer expression with side effects */ ;
A(int arg) : i(arg) { }
// ...
};
the A(int)
constructor will simply initialize i
to the value of arg
,
and the side effects in i
's default member initializer will not take
place. — end example ]
On the other hand, given
class A {
public:
A() {} // k will be initialized via default member initializer, i.e. 666
A(int b) :k(b) {} // k will be initialized via member initializer list, i.e. b
const int k = 666;
};
then for A a;
, a.k
will be initialized as 666
.