< Previous | Contents | Next >
You can also use containers as data members for your objects. That’s what I do when I define Farm. The single data member I declare for the class is simply a vector that holds Critter objects called m_Critter.
vector<Critter> m_Critters;
When I instantiate a new Farm object with:
Farm myFarm(3);
it calls the constructor:
Farm::Farm(int spaces)
{
m_Critters.reserve(spaces);
}
which allocates memory for three Critter objects in the Farm object’s m_Critter
vector.
Next, I add three critters to the farm by calling the Farm object’s Add() member function.
292 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby
myFarm.Add(Critter("Moe")); myFarm.Add(Critter("Larry")); myFarm.Add(Critter("Curly"));
The following member function accepts a constant reference to a Critter object and adds a copy of the object to the m_Critters vector.
void Farm::Add(const Critter& aCritter)
{
m_Critters.push_back(aCritter);
}
push_back() adds a copy of an object to a vector—this means that I create an extra copy of each Critter object every time I call Add(). This is no big deal in the Critter Farm program, but if I were adding many large objects, it could become a performance issue. You can reduce this overhead by using, say, a vector of pointers to objects. You’ll see how to work with pointers to objects later in this chapter.
Finally, I take roll through the Farm object’s RollCall() member function.
myFarm.RollCall();
This iterates through the vector, calling each Critter object’s GetName() member function and getting each critter to speak up and say its name.