Say I have a class called Money which has parameters Dollars and Cents
I could initialize it in the followings 2 ways:
Money a(3,15);
Allocates an Money object in the local scope.
Money* b=new Money(3,15);
Allocates a pointer-variable to the local scope, and makes the pointer "point" to a Money object that resides in the free store (assuming the allocation completed successfully, otherwise an std::bad_alloc() is thrown)
Example 1 :
Assume next scenario:
Money * b = initialize();
where
Money* initialize()
{
Money x(2 , 15);
return &x;
}
This will fail because after initialize() reaches the end of execution x is destroyed, and now b points to a location that is invalid to use and invokes Undefined Behaviour if you do used it. so instead you should allocate it with a pointer
Money* initialize()
{
return new Money(2,15);
}
The free-store is also used when you want to store and use arrays of great size.
There is a difference between the two as you noticed on the example, and that is that in the local scope x you do not need to delete the object. But when using new you will have to manually do a delete x;. Otherwise a memory leak (memory space is occupied without ever going to be used again, hence eating memory) is occurring.
See Martin York's answer for deeper knowledge beyond this post.