What do I need Pointers For?
Mainly for flexibility in creating complicated data structures. C needs pointers for returning values from function calls but C++ has references and pass-by-reference for that. C++ has structs and arrays and those can handle a considerable number of data management situations but there are times when pointers can help. Overall though, you need pointers far less in C++ than in C. Many of the times you need pointers you can use STL template classes instead, for example in maintaining a dynamic list.But template classes are in a future lesson and understanding pointers is important. Could you manage without knowing about pointers? At a pinch yes if you are only writing your own code. Definitely not if you are maintaining other developers code.
New and Delete
In exl you might have noticed the use of new and delete. These are the C++ equivalent of C's malloc() and free() for requesting and freeing memory.Both new and delete have two versions.
new() ;The first two are for pointers to single objects, the last two for arrays of object. By object I mean any size variable or object. If a new fails, an exception bad_alloc should be generated. You can prevent this exception by adding (nothrow) between new and the entity.
delete() ;
new[]() ;
delete[]() ;
int * tenints = new (nothrow) int[10] ;You should then check to see if tenints is 0. Older C++ compilers may object to (nothrow) and will return 0 if it fails.
Note. If you allocate memory through new [] then you must use delete []. Without it you'll get a leak or an exception.
Note 2. There is a version of new called placement new that lets you create a variable at a memory address. Odds are that you will never ever need it, so I've skipped it.
On the next page : Example 2

