I’m pretty sure this has been asked before, but I can’t for the life of me find it via search.
So here it goes:
What’s the difference between:
MyObj myObj;
and
MyObj myObj = MyObj();
I believe both achieve the same result, but is one better to use than the other? Assume all I want is the default constructor.
*edit – I’ve heard the first is more appropriate as the second first creates an object via the default constructor, then does an assign to myObj. The first there is no “assign” operation so the first would be “faster”. Truth?
Yes, there can be a difference.
In the first instance,
myObjis not initialized if it is a POD type otherwise it is default-initialized.In the second instance
myObjis copy-initialized from a value-initialized temporary. The temporary may (and almost certainly should) be eliminated to make the effect value-initialization.If
MyObjhas a constructor then a constructor will always be called. For the first case a default constructor must be accessible, for the second both the copy and default constructors must be accessible although only the default constructor may be called.In addition to the obvious difference between “not initialized” and value-initialized for POD types, there is a difference between default-initialized and value-initialized for non-POD types with no user-defined constructors. For these types, POD members are not initialized in default-initialization but zero-initialized in value-initialization of the parent class.