< Previous | Contents | Next >

Defining a Class

To create a new type, you can define a classcode that groups data members and member functions. From a class, you create individual objects that have their own copies of each data member and access to all of the member functions. A class is like a blueprint. Just as a blueprint defines the structure of a building, a class defines the structure of an object. And just as a foreman can create many houses from the same blueprint, a game programmer can create many objects from the same class. Some real code will help solidify this theory. I begin a class definition in the Simple Critter program with

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

258 Chapter 8 n Classes: Critter Caretaker


for a class named Critter. To define a class, start with the keyword class, followed by the class name. By convention, class names begin with an uppercase letter. You surround the class body with curly braces and end it with a semicolon.


Declaring Data Members

In a class definition, you can declare class data members to represent object qualities. I give the critters just one quality, hunger. I see hunger as a range that could be represented by an integer, so I declare an int data member m_Hunger.

int m_Hunger; // data member

This means that every Critter object will have its own hunger level, represented by its own data member named m_Hunger. Notice that I prefix the data member name with m_. Some game programmers follow this naming convention so that data members are instantly recognizable.


Declaring Member Functions

In a class definition, you can also declare member functions to represent object abilities. I give a critter just onethe ability to greet the world and announce its hunger levelby declaring the member function Greet().

void Greet(); // member function prototype

This means that every Critter object will have the ability to say hi and announce its own hunger level through its member function, Greet(). By convention, member function names begin with an uppercase letter. At this point, Ive only declared the member function Greet(). Dont worry, though, Ill define it outside of the class.


Hi n t

image

You might have noticed the keyword public in the class definition. You can ignore it for now. You’ll learn more about it a bit later in this chapter, in the section, “Specifying Public and Private Access Levels.”

image