Given two classes with different constructors:
#include <iostream>
struct A {
int x;
A() {};
};
struct B {
int x;
B() = default;
};
int main() {
int x = 5;
x = 7;
printf("before: %d\n", x);
new(&x) A();
printf("%d\n", x);
new(&x) B();
printf("%d\n", x);
}
Output is:
before: 7
7
0
Why default ctor zero-initializes int x?
You used value initialization (
new A();) which is different from default initialization (new A;). Notice the parenthesis.For value initialization :
And :
And, on the definition of "user-provided" :
Ahas a user provided constructor so it falls in the first case. The just calls its constructor which initializes nothing.B's constructor is explicitly defaulted so it isn't user provided, and it is also not deleted, so it falls into the second case. It is zero-initialized then default initializated.