Now you've been able to define a class which can contain, modify, and extract data about salsa. But lets say you're the president of a new chimichanga manufacturing company, and you'd like to make this class available to the public for world wide consumption, but you'd like to keep the internal workings of your chmichanga top secret so that those New Yorkers don't go stealing your secret recipe. How would you do this? The last example wouldn't quite work because allthough you provided methods to access the class data, the data itself was still just as accessible without using any methods. This is where public and private come in. Here is a class which will protect the top secret proprietary information: class Chimichanga { public: void SetChunkiness(int chunky) { chunkiness = chunky; } void SetSpiciness(int spicy) { spiciness = spicy; } char* GetRecipe(void) { return strdup("Haha, Nice try buddy."); } int GetQuality(void) { return ((chunkiness + spiciness) / 2); } private: int chunkiness; int spiciness; char* recipe = "Top Secret"; }; In the previous examples of classes that we've shown you, each class has had only one section, labeled as public. In the above class however, there are two sections, one labeled as public and one labeled as private. This has the effect that you can probably guess at: anything defined in the public section can be accessed anywhere in your program, but anything defined in the private section can only be accessed from other methods within that same class. Note that if you don't label a public or private section in your class, then everything defaults to private, which is easy to forget if you're just making a small class with all public members (and in that case, you should probably use a struct anyway). |