Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 141

6


Declaring a Class............................................................................................


Declaring a class tells the compiler about the class. To declare a class, use the classkey-
word followed by the class name, an opening brace, and then a list of the data members
and methods of that class. End the declaration with a closing brace and a semicolon.
Here’s the declaration of a class called Cat:


class Cat
{
unsigned int itsAge;
unsigned int itsWeight;
void Meow();
};


Declaring this class doesn’t allocate memory for a Cat. It just tells the compiler what a
Catis, what data members it contains (itsAgeand itsWeight), and what it can do
(Meow()). Although memory isn’t allocated, it does let the compiler know how big a Cat
is—that is, how much room the compiler must set aside for each Catthat you will create.
In this example, if an integer is four bytes, a Catis eight bytes big:itsAgeis four bytes,
and itsWeightis another four bytes. Meow()takes up only the room required for storing
information on the location of Meow(). This is a pointer to a function that can take four
bytes on a 32-bit platform.


A Word on Naming Conventions ..................................................................


As a programmer, you must name all your member variables, member functions, and
classes. As you learned on Day 3, “Working with Variables and Constants,” these should
be easily understood and meaningful names. Cat,Rectangle, and Employeeare good
class names. Meow(),ChaseMice(), and StopEngine()are good function names because
they tell you what the functions do. Many programmers name the member variables with
the prefix “its,” as in itsAge,itsWeight, and itsSpeed. This helps to distinguish mem-
ber variables from nonmember variables.


Other programmers use different prefixes. Some prefer myAge,myWeight, and mySpeed.
Still others simply use the letter m(for member), possibly with an underscore (_) such as
mAgeor m_age,mWeightor m_weight, or mSpeedor m_speed.


Some programmers like to prefix every class name with a particular letter—for example,
cCator cPerson—whereas others put the name in all uppercase or all lowercase. The
convention that this book uses is to name all classes with initial capitalization, as in Cat
and Person.


Similarly, many programmers begin all functions with capital letters and all variables
with lowercase. Words are usually separated with an underscore—as in Chase_Mice—
or by capitalizing each word—for example,ChaseMiceor DrawCircle.

Free download pdf