It is worth clarifying a few points. For a class with members as follows,
class MyClass {
public:
int var;
float* ptr;
double array[3];
MyStruct data;
unique_ptr<MyStruct> smart_ptr;
...
}
A default constructor defined by the user as follows,
MyClass() : var{}, ptr{}, array{}, data{}, smart_ptr{} {}
will lead to value initialization of the member variables. If a member variable is a class type then its value initialization happens under certain conditions as described in that link.
While defining an object with or without braces (MyClass obj{};
or MyClass obj;
), this default constructor will lead to value initialization of the class members.
Suppose, MyClass
has a default constructor in one of the following forms:
MyClass() {};
MyClass() = default;
(See here about further information on these two forms for the default constructor.) As far as defining and initializing objects of MyClass
is concerned, MyClass() {};
leads to default initialization, while MyClass() = default;
leads to value initialization when defining an object with braces (MyClass obj{};
). This is because MyClass() {};
is a user defined default constructor with an empty initialization list and an empty body, which will lead to default initialization of the members. On the other hand, MyClass() = default;
leads to a compiler defined default constructor, which will correctly lead to value initialization when defining an object with braces. See here about how even the = default;
could go wrong.
MyClass instance()
with brackets? :| – Helluvadefault
would be expected to default-initialise members. Default-initialisation is not always equivalent to zero-initialisation. – Heder