Based on my experience there is two ways to instantiate an object.
Method 1:
Car* car1 = new Car();
Method 2:
Car car1;
So, my question is what really is the difference in the two methods. Does
one get stored on the stack while the other gets stored on the heap?
Using "new" instantiates the object "dynamically"; the area of memory where
the object is constructed happens to be called the "free store". The term
"the heap" is often used synonymously (and purists around here would be
happy to point out the differences), but those differences do not become
important unless you insist on using library functions such as malloc and
free to manage storage, rather than operators new and delete.
When you do it the other way,
Car car1;
then the object may end up just about anywhere, depending on the context of
that line of code. If it is a stand-alone definition at block scope or
namespace scope, the object ends up in automatic storage (on the stack,
usually), or static storage (a fixed location in memory, such as that
occupied by all "extern" data), respectively. If, however, the line is
part of a class definition, then it all depends on how the enclosing class
is instantiated! for example, given:
class Fleet {
Truck truck1;
Car loaners[10];
Car car1;
Bicycle b;
};
Then you might say:
Fleet f1;
Fleet *fleetp = new Fleet;
In that case, f1 is automatic (in a block) or static (namespace scope), but
the object pointed to be fleetp is dynamic (and contains a Car, among other
things.)
So as you can see, the question isn't as simple as you the one you asked.
Is one
better than the other?
Sometimes one is better than the other for some particular purpose. Time to
get yourself a good introductory C++ book and dive in.
How is one to reference the difference between the
two, that is is the firt method called instantiation by ? while the second
one is called instantiation by ?
Because the non-dynamic one can appear in different contexts, I'm not sure
how much good it would really do to label it instantiation by _____ . I
just call it creating or instantiating an object, and when using "new" I
add the word "dynamically"...
-leor