Search code examples
c++constructorexplicit-constructor

Difference in object construction using "X x(42)" and "X x = 42"?


Let's say we have class X with defined constructor X(int value).

Is this semantically equivalent or not?

X x = 42;
X x(42);

I believe the difference will appear only if we add explicit keyword to constructor of X. Otherwise compiler will reduce expression X x = 42; to X x(42);

Please, correct me if I'm wrong.


Solution

  • The form

    X x = 42;
    

    requires that the constructor be non-explicit and that there be an accessible copy-constructor. The implementation is allowed to construct a temporary and copy it over, but no implementation I know of does that.