Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 842
Nick Avatar asked Dec 21 '10 22:12

Nick


People also ask

What are the two main ways to instantiate an object?

There are three different ways of instantiating an object through constructors: Through Default constructors. Through Parameterized constructors. Through Copy constructors.

What method is called to instantiate an object?

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.

How many ways can you initialize an object in C++?

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.

What is object explain instantiation an object of a class?

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.


1 Answers

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.

like image 192
CB Bailey Avatar answered Nov 15 '22 19:11

CB Bailey