Now that you've seen how a class with public and private sections is defined, lets take a look at what you can and can't do to use our Chimichanga class. Do's Chimichanga specialblend; specialblend.SetChunkiness(95); specialblend.SetSpiciness(85); cout << "SpecialBlend's Rating O' Quality: "; cout << specialblend.GetQuality() << endl; cout << "The Top Secret Recipe is: "; cout << specialblend.GetRecipe() << endl; All of the class members called in the above class are methods from the public section of the class, so it is okay to call them. The output from the above code would have been: SpecialBlend's Rating O' Quality: 90 The Top Secret Recipe is: Haha, Nice try buddy! Now for some Don'ts Chimichanga specialblend; specialblend.chunkiness = 70; cout << "Special Blend's Chunkiness: "; cout << specialblend.chunkiness << endl; cout << "The Top Secret Recipe is: "; cout << specialblend.recipe << endl;
All three of the uses of specialblend above are illegal, because they try
to directly access members which were declared as being private in the class
definition. If you were to try and compile this code, the compiler would
give you an error like " When using classes, a good strategy to use is "If it doesn't HAVE to be public, then it should be private". In most cases it is a good idea to make all data private, and the methods to access that data public. However, you can have public data and private methods as well. And there you have it, a class which will protect Special Blend Chimichanga's secret recipe from evil New York mega-corporations. |