Nick
Nick

Reputation: 2969

C++ Instantiate an object from a class two different ways

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?

Upvotes: 9

Views: 9901

Answers (3)

CodeMonkey
CodeMonkey

Reputation: 12444

Without many explanations - The first one uses the default constructor in order to initialize your myObj. The second one actually creates a temporary instance, and then is using a copy constructor to initialize myObj. (remember that a default copy constructor is also created, and not just a default constructor)

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 793289

Yes, there can be a difference.

In the first instance, myObj is not initialized if it is a POD type otherwise it is default-initialized.

In the second instance myObj is copy-initialized from a value-initialized temporary. The temporary may (and almost certainly should) be eliminated to make the effect value-initialization.

If MyObj has 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.

Upvotes: 9

Edward Strange
Edward Strange

Reputation: 40895

The former is a declaration, the latter an initialization.

If MyObj is not a POD then there's really no difference except that a copy constructor must exist and be accessible in the latter case (even though it's not called).

If MyObj is a POD then the former does not initialize it, content of MyObj member variables will be unspecified. The latter is the only way to 'zero' initialize a non-aggregate POD.

Upvotes: 4

Related Questions