There are two main ways of instantiating objects in C++: stack and heap (or free store). For example:
void func()
{
// On the stack:
Widget blah;
// On the heap:
Widget * foo = new Widget;
delete foo;
}
The advantage of stack objects/variables is that they tend to be a little a faster to allocate/access, and they are slightly easier to work with. However, the stack is a limited size, and the data is usually limited to local scope (with the exception of global variables, which are usually inadvisable). That is, the blah
object in the example above will be automatically destroyed as soon as func()
ends. There's nothing you can do about that. Any pointers to stack objects/variables therefore become invalid (aka 'dangling') when the original item goes out of scope.
The heap is (typically) much bigger, so it can cope with a lot more data than the stack. It tends to be slightly slower, but it has the advantage of letting you reallocate things at run-time. By contrast, stack objects/variables (and especially arrays) are fixed at compile-time.
Additionally, after an object has been allocated on the heap, you can leave it there for as long as you need it, maintaining valid pointers to it. In the past, you would have to call delete
eventually to avoid a memory leak. In modern C++, smart pointers are encouraged instead (e.g. std::shared_ptr
).
As an additional note, it gets slightly more complex when declaring members of a class. If the object is instantiated on the stack, then any of its direct members (i.e. members by composition) will be on the stack too. If the object is instantiated on the heap, then all of its members will be on the heap.