< Previous | Contents | Next >

Using Object Data Members

One way to use aggregation when youre defining a class is to declare a data member that can hold another object. Thats what I did in Critter with the following line, which declares the data member m_Name to hold a string object.

string m_Name;

Generally, you use aggregation when an object has another object. In this case, a critter has a name. These kinds of relationships are called has-a relationships.

Using Aggregation 291


I put the declaration for the critters name to use when I instantiate a new object with:

Critter crit("Poochie");

which calls the Critter constructor:

Critter::Critter(const string& name): m_Name(name)

{}

By passing the string literal "Poochie", the constructor is called and a string object for the name is instantiated, which the constructor assigns to m_Name. A new critter named Poochie is born.

Next, I display the critters name with the following line:

cout << "My critter’s name is " << crit.GetName() << endl;

The code crit.GetName() returns a copy of the string object for the name of the critter, which is then sent to cout and displayed on the screen.