That is correct behaviour for the respective types, everywhere.
Primitive types are initialized differently depending on whether you explicitly request the default value (value initialization) or don't mention the initialization (default initialization).
If you construct primitive type without mentioning initialization (this is called default initialization), the value is random:
int x;
struct Y {
int x;
} x;
int *x = new int;
are all default initializations and will contain random value.
But if you mention the initializer, it becomes value initialization and the value is initialized to appropriate "zero" (0
for numbers, 0
/nullptr
for pointers):
int x = 0;
int x = int();
struct Y {
int x;
Y() : x() {} // the x() is important
} y;
struct Z {
int x;
} z = {};
int *x = new int();
are all value initializations and C++11 adds the following forms
int x{};
struct Y {
int x;
Y() : x{} {}
} y;
struct Z {
int x;
} z{};
int *x = new int{};
Beware of
int x(); // function, NOT A VARIABLE
it declares a function taking no arguments and returning int
. This is called the "most vexing parse".