< Previous | Contents | Next >

Accessing Data Members

Its time to put these critters to work. Next, I give my first critter a hunger level.

crit1.m_Hunger = 9;

The preceding code assigns 9 to crit1s data member m_Hunger. Just like when you are accessing an available member function of an object, you can access an available data member of an object using the member selection operator.

To prove that the assignment worked, I display the critters hunger level.

cout << "crit1’s hunger level is " << crit1.m_Hunger << ".\n";

The preceding code displays crit1s data member m_Hunger and correctly shows 9. Just like when you are assigning a value to an available data member, you can

260 Chapter 8 n Classes: Critter Caretaker


get the value of an available data member through the member selection operator.

Next, I show that the same process works for another Critter object.

crit2.m_Hunger = 3;

cout << "crit2’s hunger level is " << crit2.m_Hunger << ".\n\n";

This time, I assign 3 to crit2s data member m_Hunger and display it.

So, crit1 and crit2 are both instances of Critter, and yet each exists independently and each has its own identity. Also, each has its own m_Hunger data member with its own value.