Why `default` ctor zero-initializes class members?

150 views Asked by At

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?

1

There are 1 answers

6
François Andrieux On

You used value initialization (new A();) which is different from default initialization (new A;). Notice the parenthesis.

For value initialization :

if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;

And :

if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;

And, on the definition of "user-provided" :

A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration.

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