Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Value initialization

Value initialization zero-initializes scalars, works element by element for arrays, and combines conditional zero-initialization with default-initialization for classes. It does not mean that every object will contain only zero values.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

T(); new T(); T object{}; // {} uses list-initialization rules and does not always imply value-initialization

Value initialization occurs in contexts including T() and new T(). For scalar types, it means zero-initialization: an int receives 0, a bool receives false, and a pointer receives a null pointer value. For arrays, each element is value-initialized. References cannot be initialized this way.

For a class, the constructor for default-initialization is selected. If it is not user-provided, the object is first zero-initialized; default-initialization then always follows. The constructor can establish nonzero values. A user-provided constructor skips this preliminary zero-initialization, so scalar members it leaves uninitialized are not guaranteed to be zero.

Counter() = default; on its first declaration is not user-provided, even though it is user-declared. In contrast, a constructor with a {} body is user-provided, as is a constructor defined with = default only after its first declaration. This distinction determines whether preliminary zero-initialization occurs.

The spelling T object{}; invokes list-initialization rules. For scalars and non-aggregate classes with a default constructor, an empty list leads to value-initialization; aggregates follow different rules. Therefore, do not equate every use of {} with this mechanism. T object(); declares a function, not an object. A local automatic variable int number; is default-initialized rather than value-initialized and does not receive zero through that initialization.

Examples

#include <iostream>

struct Counter {
    int count;
    Counter() = default;
};

struct Configured {
    int count;
    Configured() : count(7) {}
};

int main() {
    int number = int();
    Counter counter{};
    Configured configured{};
    std::cout << number << ' ' << counter.count << ' '
              << configured.count << '\n';
}

Result

0 0 7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources