Reputation: 3706
What is difference between these two statements with respect to dynamic memory initialization of object :-
class_name *obj = new class_name;
class_name obj = class_name();
Upvotes: 0
Views: 2589
Reputation: 2947
The first example works roughly like this:
The second example:
Edit: Actually, what I've written for the second example above, is not right (maybe it's not wrong, too). I don't know the standard here, but with VC12 (optimizations off) the code doesn't create an temporary object. It just calls the default constructor for an object on the stack. And the code doesn't compile if there's a private assignment operator - as James writes in his comment.
Upvotes: 3
Reputation: 153929
The first defines a pointer to class_name
, dynamically
allocates an object of that type, and initializes the pointer
with its address. The lifetime of the object itself is until
you explicitly delete it. If the class_name
has a default
constructor, that is called; otherwise, the object is not
initialized.
The second defines an instance of a class_name
; formally, it
constructs a temporary of that type, using the default
constructor if one is defined, or zero initialization if not,
and copy constructs the defined instance from that. The
compiler is allowed to elide this copy construction, however
(and all that I know of do), and construct the defined object
directly. (It must still verify that there is an accessible
copy constructor, however.) The lifetime of the defined object
is until it goes out of scope.
In general, we avoid the first form, unless we really need the explicit lifetime.
Upvotes: 2
Reputation: 145279
Hopefully you have related the assignment/question text correctly. It's subtle. The "dynamic" has nothing to do with the dynamic allocation in the first statement.
The ()
parenthesis ensures a C++03 value initialization, which for a POD type means zeroing. Without it (first statement), if the class is a POD its members needs not be initialized. I would have to check the standard for the more general case, but I think, now that you know what the question is about, that's something you can do on your own.
Upvotes: 1
Reputation: 35408
This:
class_name *obj = new class_name;
creates an object on the heap, you will need to delete it via delete
to avoid memory leaks.
This:
class_name obj = class_name();
creates an object on the stack, the object will be deleted when it goes out of scope.
Upvotes: 1
Reputation: 2279
First is dynamically allocated. Second is statically allocated, but value initialized.
Upvotes: 1