Chapter 23. Pointers to Objects
In This Chapter
Adding member functions to a class
Defining the member function
Invoking the member function
Accessing one member from another member
Overloading member functions
Chapters 17 and 18 focus on various aspects of the care and feeding of pointers. Surely, you think, nothing more can be said on the subject. But I hadn't introduced the concept classes before those chapters. In this chapter, I describe the intersection of pointer variables and object-oriented programming. This chapter deals with the concept of pointers to class objects. I'll describe how to create one, how to use it, and how to delete it once you're finished with it.
Pointers to Objects
A pointer to a programmer-defined type such as a class works essentially the same as a pointer to an intrinsic type:
int nInt; int* pInt = &nInt; class Savings { public: int nAccountNumber; double dBalance; }; Savings s; Savings* pS = &s;
The first pair of declarations defines an integer, nInt
, and a pointer to an integer, pInt
. The pointer pInt
is initialized to point to the integer nInt
.
Similarly, the second pair of declarations creates a Savings
object s
. It then declares a pointer to a Savings
object, pS
, and initializes it to the address of s
.
The type of pS
is "pointer to Savings
" which is written Savings*
.
I feel like the late Billy Mays when I say, "But wait! There's more!" The similarities continue. The following statement assigns the value 1
to the int
pointed at by pInt
:
*pInt = 1;
Similarly, ...
Get Beginning Programming with C++ For Dummies® now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.