Section 2 - Classes You Define

6A.2.1 Defining a Class

We have used classes that were defined for us by C++:  The string class was an example.  We used it to declare string objects that our program used.  Now we wish to define our own classes. decorative flowers

We are now going to accompany our main class with one or more new classes.  We will define these new classes in the same .cpp file, below (or above) the main() method. 

When you think of defining classes, you should think of defining your own custom-made data type.  Floats, ints, doubles, even strings:  these are all boring.  We want to define a new class that has a little flash and appeal.  And what could be more entertaining than a pet?  (I don't know, I don't have one, but all my neighbors do.)

So we will create a new data type, called Pet, and we will decide that a Pet will always have four things.

And with that, we can create a class definition:

class Pet
{
public:
// member data
string petsName;
string ownersName;
double weight;
long numberOfLimbs;
};

This is the basic idea.  We use the word class followed by the name we want to give this new data type.  Then we open a brace and place the definition of the class between the opening brace and the closing brace.  We see the keyword, public: used to describe the data in the class as publicly accessible (which we'll talk about later).

We build our class from any old "spare parts" we have lying around: Strings, doubles, even other pre-defined classes. 

And, once we define this new class, Pet,  how do we use it?  Since it is a data type, like any other, we use it by declaring variables of that type.  These variables behave more like strings than like the primitive types. You'll recall that the String class was a little more complex than the primitive int or double type.  Here's an example of the entire program minus the details.  Notice that we first present the new class definitions, followed by the main() method.

class Pet
{
public:
// member data
string petsName;
string ownersName;
double weight;
long numberOfLimbs;
};

int main()
{
// declare a couple Pet objects
Pet mikesDog, noisyDog;

// ... a little later on, perhaps make an assignment statement
noisyDog = mikesDog;

}

Things to observe:

This is a good start. Let's see an entire program using Pet objects.