Sams Teach Yourself C++ in 21 Days

(singke) #1
Accessing the members of an object when using a pointer is a little more complex. To
access the Catobject on the free store, you must dereference the pointer and call the dot
operator on the object pointed to by the pointer. It is worth repeating this. You must first
dereference the pointer. You then use the dereferenced value—the value being pointed
to—along with the dot operator to access the members of the object. Therefore, to access
the GetAgemember function of an object pointed to by pRags, you write
(*pRags).GetAge();
As you can see, parentheses are used to ensure that pRagsis dereferenced first—before
GetAge()is accessed. Remember, parentheses have a higher precedence than other
operators.
Because this is cumbersome, C++ provides a shorthand operator for indirect access: the
class member accessoperator (->), which is created by typing the dash (-) immediately
followed by the greater-than symbol (>). C++ treats this as a single symbol. Listing 8.6
demonstrates accessing member variables and functions of objects created on the free
store.

240 Day 8


Because the class member access operator (->) can also be used for indirect
access to members of an object (through a pointer), it can also be referred
to as an indirection operator. Some people also refer to it as the points-to
operator because that is what it does.

NOTE

LISTING8.6 Accessing Member Data of Objects on the Free Store
1: // Listing 8.6 - Accessing data members of objects on the heap
2: // using the -> operator
3:
4: #include <iostream>
5:
6: class SimpleCat
7: {
8: public:
9: SimpleCat() {itsAge = 2; }
10: ~SimpleCat() {}
11: int GetAge() const { return itsAge; }
12: void SetAge(int age) { itsAge = age; }
13: private:
14: int itsAge;
15: };
16:
17: int main()
18: {
Free download pdf