< Previous | Contents | Next >

Using Pointers to Objects

So far, the Pointing program has worked only with values of a built-in type, int. But you can use pointers with objects just as easily. I demonstrate this next with the following lines, which create str, a string object equal to "score", and pStr, a pointer that points to that object.

string str = "score";

string* pStr = &str; //pointer to string object

pStr is a pointer to string, meaning that it can point to any string object. Another way to say this is to say that pStr can store the address of any string object.

You can access an object through a pointer using the dereference operator. Thats what I do next with the following line.

cout << "*pStr is: " << *pStr << "\n";

By using the dereference operator with *pStr, I send the object to which pStr

points (str) to cout. As a result, the text score is displayed.

You can call the member functions of an object through a pointer the same way you can call the member functions of an object through an iterator. One way to do this is by using the dereference operator and the member access operator, which is what I do next with the following lines.

cout << "(*pStr).size() is: " << (*pStr).size() << "\n";

The code (*pStr).size() says, Take the result of dereferencing pStr and call that objects size() member function.Because pStr refers to the string object equal to "score", the code returns 5.


Hi n t

image

Whenever you dereference a pointer to access a data member or member function, surround the dereferenced pointer with a pair of parentheses. This ensures that the dot operator will be applied to the object to which the pointer points.

image


Just as with iterators, you can use the -> operator with pointers for a more readable way to access object members. Thats what I demonstrate next with the following line.

cout << "pStr->size() is: " << pStr->size() << "\n";

Understanding Pointers and Constants 231


The preceding statement again displays the number of characters in the string object equal to "score"; however, Im able to substitute pStr->size() for (*pStr).size() this time, making the code more readable.