< Previous | Contents | Next >

Introducing the Simple Critter

Program

The Simple Critter Program defines a brand-new type called Critter for creating virtual pet objects. The program uses this new type to create two Critter objects. Then, it gives each critter a hunger level. Finally, each critter offers a greeting and announces its hunger level to the world. Figure 8.1 shows the results of the program.


image

Figure 8.1

Each critter says hi and announces how hungry it is.


You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 8 folder; the filename is simple_critter.cpp.

//Simple Critter

//Demonstrates creating a new type #include <iostream>

using namespace std;

Defining New Types 257


class Critter // class definition –– defines a new type, Critter

{

public:

int m_Hunger; // data member

void Greet(); // member function prototype

};


void Critter::Greet() // member function definition

{

cout << "Hi. I’m a critter. My hunger level is " << m_Hunger << ".\n";

}


int main()

{

Critter crit1; Critter crit2;


crit1.m_Hunger = 9;

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


crit2.m_Hunger = 3;

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


crit1.Greet(); crit2.Greet();


return 0;

}