More Class Basics


So now you've seen how to declare a class. However, a class with nothing in it isn't a very interesting class. So first we'll add some data about salsa to our salsa class.

class Salsa {
  public:
    int chunkiness;
    int spiciness;
};

In the above class, we define variables to store two very important pieces of data, the chunkiness and spiciness of salsa. Information in classes is stored in variables which are declared the same way as you would declare any other variable in C++. (And for those of you wondering about that line which says "public:", don't fret. All will be revealed in time.)

But of course, salsa isn't much good to us unless we are able to use it. To puts some salsa in our program, we need to declare a object of the Salsa class, and then use that object. Here's a quick example:

#include <iostream.h>

/ Insert code from above here

void main(void) {
  Salsa picante;

  picante.chunkiness = 100;
  if (picante.chunkiness > 90) {
    cout << "This is very chunky salsa!" << endl;
  }
}

Data members in a class are accessed like data in a struct: the name of the struct/class variable followed by the data member, with a "." separating the two.


Table of Contents

Classes | More Class Basics | Class Methods | Public and Private
Using Public and Private | Classes and Pointers | Exercises