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?
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.
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.
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.
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 delete
d. 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.
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