< Previous | Contents | Next >

Calling a Constructor Automatically

You donā€™t explicitly call a constructor; however, whenever you instantiate a new object, its constructor is automatically called. In main(), I put my constructor into action with the following code:

Critter crit(7);

When crit is instantiated, its constructor is automatically called and the message A new critter has been born! is displayed. Then, the constructor assigns 7 to the objectā€™s m_Hunger data member.

To prove that the constructor worked, back in main(), I call the objectā€™s Greet() member function and sure enough, it displays Hi. Iā€™m a critter. My hunger level is 7.

264 Chapter 8 n Classes: Critter Caretaker