Ambarish Ambarish - 1 year ago 90
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download