I think a lot of this is, well, not too correct.
Largely, pointers are needed only when memory has to be allocated dynamically, however there are various other
edge cases as well. But for the C++ student, the edge cases can be ignored. So the real question is: "when do I
need dynamic memory allocation"? You need it in a couple of cases:
1. You need to allocate a number of elements [in an array] that is known only at runtime, not at compile time.
2. You need the lifetime of a variable to exceed the scope in which it is declared. Let's say I have a Thread object
that encapsulates a thread of execution. I have a function that creates a Thread object and wants to return it:
1 2 3 4
|
Thread* MakeThread() {
Thread* thd = new Thread();
return thd;
}
|
I want the lifetime of the Thread instance to exceed that in which it is declared (because in this case I want to return
it to the caller): it is instantiated within the function MakeThread(), meaning that it would be destroyed at the end of
MakeThread() if I just allocated it on the stack (instead of dynamically allocating it).