Ambarish Ambarish - 6 months ago 53
C++ Question

In C++, what is the difference between X x = X(); type declaration and X x; declaration where X is the class

In my code I encountered above kind of scenario. Under what circumstances we need to use above style of object creation? Cant we simply create object X x? What thing we have achieved in X x = X(); type declaration?


There is difference. X x = X() requires the copy constructor to be accessible.

For the following class:

struct Foo
    Foo() = default;
    Foo(Foo const&) = delete;
    void* ptr;

This will compile:

Foo foo;

and this won't:

Foo foo = Foo();

Furthermore, the first syntax results in default-initialization, so ptr has undetermined value, while the second would zero-initialize it to nullptr (if the copy constructor wasn't deleted or inaccessible).

The reasonable default is neither of those - uniform initialization syntax (available since C++11):

Foo foo{};

While less uniform than the name suggests, it leaves your object zero-initialized and is immune to most vexing parse.