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 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.

Leave a Comment