This chapter discusses pointers—one of C++’s most powerful, yet challenging to use, capabilities. We’ll help you determine when it’s appropriate to use pointers, and show you how to use them correctly and responsibly.
In Chapter 6, we saw that references can be used to perform pass-by-reference. Pointers also enable pass-by-reference and can be used to create and manipulate dynamic data structures that can grow and shrink, such as linked lists, queues, stacks and trees. This chapter explains basic pointer concepts. Chapter 19 presents examples of creating and using pointer-based dynamic data structures.
We also show the intimate relationship among built-in arrays and pointers. C++ inherited built-in arrays from the C programming language. As we saw in Chapter 7, the C++ Standard Library classes array
and vector
provide more robust implementations of arrays as full-fledged objects.
Similarly, C++ actually offers two types of strings—string
class objects (which we’ve been using since Chapter 3) and C-style, pointer-based strings (C strings). This chapter briefly introduces C strings to deepen your knowledge of pointers and built-in arrays. C strings were widely used in older C and C++ software. We discuss C strings in depth in Appendix F.
In new software development projects, you should favor array
and vector
objects to builtin arrays, and string
objects to C strings.
We’ll examine the use of pointers with class objects in Chapter 12, where we’ll see that the “polymorphic processing” associated with object-oriented programming is performed with references and pointers.