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?
There are three different ways of instantiating an object through constructors: Through Default constructors. Through Parameterized constructors. Through Copy constructors.
Instantiation: The new keyword is a Java operator that creates the object. As discussed below, this is also known as instantiating a class. Initialization: The new operator is followed by a call to a constructor.
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
An object is essentially an instance (instantiation) in a class in object-oriented programming. These properties (or variables) can be viewed as data describing the objects that are created from a class. For example, a class may represent a new employee.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With