Class Methods


So now you've seen how to use a class in a program. But right now I bet you're asking "What's so special about classes? They look exactly like structs."

However, objects in an object-oriented language not only allow you to store information, they also allow you to access that information. This is where methods come in. A method is simply a function defined within a class which can act upon data in that class. Here's one example:

class Salsa {
  public:
    int GetChunkiness(void) { 
      return chunkiness; 
    }
    int GetSpiciness(void) { 
      return spiciness; 
    }
    int GetQuality(void) {
       return ((chunkiness + spiciness) / 2);
    }
    void SetChunkiness(int chunky) {
      chunikiness = chunky;
    }
    void SetSpiciness(int spicy) {
      spiciness = spicy;
    }
    int chunkiness;
    int spiciness;
};

Here we see our new salsa class with five methods in adition to the two data variables we saw before. These methods provide an interfce with which to manipulate the data stored in the Salsa class. Using these methods, we can manipulate and extract data from a Salsa object without having to know what data types are used to store the data. This is known as data encapsulation, which is an important concept in object-oriented programming. An example of some code which uses the new Salsa class is below.

#include <iostream.h>

/ Insert Salsa here

void main(void) {
  Salsa riogrande;
  riogrande.SetSpiciness(75);
  riogrande.chunkiness = 85;
  cout << "RioGrande Salsa has a quality rating of ";
  cout << riogrande.GetQuality() << endl;
}

Here we see that even though we have defined methods to access the data in a class, we can still access the data directly like we did before.


Table of Contents

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