What is difference between instantiating an object using new vs. without
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.
One more obvious difference is when accessing the variables and methods of t.
Time t (12, 0, 0);
t.GetTime();
Time* t = new Time(12, 0, 0);
t->GetTime();
As far as the constructor is concerned, the two forms are functionally identical: they'll just cause the constructor to be called on a newly allocated object instance. You already seem to have a good grasp on the differences in terms of allocation modes and object lifetimes.