< Previous | Contents | Next >

Introducing the Constructor Critter

Program

The Constructor Critter program demonstrates constructors. The program instantiates a new critter object, which automatically invokes its constructor. First, the constructor announces that a new critter has been born. Then, it assigns the value passed to it to the critters hunger level. Finally, the program calls the critters greeting member function, which displays the critters hunger level, proving that the constructor did in fact initialize the critter. Figure 8.2 shows the results of the program.


image

Figure 8.2

The Critter constructor initializes a new object’s hunger level automatically.


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 constructor_critter.cpp.

//Constructor Critter

//Demonstrates constructors #include <iostream>

using namespace std;


class Critter

{

262 Chapter 8 n Classes: Critter Caretaker


public:

int m_Hunger;


Critter(int hunger = 0); // constructor prototype void Greet();

};


Critter::Critter(int hunger) // constructor definition

{

cout << "A new critter has been born!" << endl; m_Hunger = hunger;

}


void Critter::Greet()

{

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

}


int main()

{

Critter crit(7); crit.Greet();


return 0;

}