Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between instantiating an object using new vs. without

In C++,

Aside from dynamic memory allocation, is there a functional difference between the following two lines of code:

Time t (12, 0, 0); //t is a Time object  Time* t = new Time(12, 0, 0);//t is a pointer to a dynamically allocated Time object 

I am assuming of course that a Time(int, int, int) ctor has been defined. I also realize that in the second case t will need to be deleted as it was allocated on the heap. Is there any other difference?

like image 261
manzy704 Avatar asked Sep 09 '10 05:09

manzy704


People also ask

What is the difference between initializing and instantiating?

Initialization-Assigning a value to a variable i.e a=0,setting the initial values. Instantiation- Creating the object i.e when u r referencing a variable to an object with new operator.

Why do you need to use new operator during instantiation?

When you are done using the variable, you would need to call delete on it to avoid a memory leak. Without the new operator, when the variable goes out of scope the memory will be freed automatically.

What does it mean to instantiate an object in Javascript?

To instantiate is to create such an instance by, for example, defining one particular variation of an object within a class, giving it a name and locating it in some physical place.


1 Answers

The line:

Time t (12, 0, 0); 

... allocates a variable of type Time in local scope, generally on the stack, which will be destroyed when its scope ends.

By contrast:

Time* t = new Time(12, 0, 0); 

... allocates a block of memory by calling either ::operator new() or Time::operator new(), and subsequently calls Time::Time() with this set to an address within that memory block (and also returned as the result of new), which is then stored in t. As you know, this is generally done on the heap (by default) and requires that you delete it later in the program, while the pointer in t is generally stored on the stack.

N.B.: My use of generally here is speaking in terms of common implementations. The C++ standard does not distinguish stack and heap as a part of the machine, but rather in terms of their lifetime. Variables in local scope are said to have "automatic storage duration," and are thus destroyed at the end of local scope; and objects created with new are said to have "dynamic storage duration," and are destroyed only when deleted. In practical terms, this means that automatic variables are created and destroyed on the stack, and dynamic objects are stored on the heap, but this is not required by the language.

like image 191
greyfade Avatar answered Sep 28 '22 09:09

greyfade